【发布时间】:2019-02-01 07:18:48
【问题描述】:
我需要动态捕获 getter 方法的字段名称以进行动态验证和动态格式化。 什么是最好和最有效的方法。
public class Emp{
private String firstName;
private String lastName;
private String address;
private int age;
// getter and setters
}
public class MyImplementationClass{
public execute(Emp emp){
String fName=emp.getFirstName();
// field name need to be taken here using 'emp.getFirstName()'
// need field name and value of return value of 'emp.getFirstName()' for dynamic validation and dynamic formatting.
// here need to call method validateAndFormat() with field name and value.
}
}
private String validateAndFormat(String fieldName,String value){
// read the dynamic validation settings from the xml and validate/reformat the value
// this method will validate the field according to xml and return reformatted value.
}
private int validateAndFormat(String fieldName,int value){
//...
}
动态验证设置
<message>
<element field="firstName" length="22" defaultVal=""></element>
<element field="lastName" length="20" defaultVal="ibft"></element>
<element field="address" length="NA" defaultVal=""></element>
<element field="age" length="NA" defaultVal=""></element>
</message>
【问题讨论】:
-
请更具体。从您的示例中,我无法理解您真正想要的是什么。如果您调用 getFirstName,那么您想动态找出该方法返回的字段,即使该字段不像方法名称那样被调用?
-
但是
emp.getFirstName()会返回名字,而不是字段——它甚至可能不会直接由字段支持。该字段是一个实现细节,您不需要关心它。您能否提供有关您要实现的目标的更多信息?如果您确实拥有字段名称,那么您的其余代码会是什么样子? -
我需要字段名和getter的值来验证和重新格式化..
-
我不明白你想要什么,但如果你需要获取方法名称,我发现关于反射 api 的问题是 link。