任何人都可以澄清一下,当我在java中调用类的get/set方法时是否可以获取类属性名称。
我在网上看到一些内容,可以使用反射概念获取类属性名称。
我的情况:
尝试编写一个方法来检查属性值是否为 null/空,并在属性值为 null/空时返回属性名称。
示例:
类别:
public class MyClass {
private appName;
public void setAppName(String appName) {
this.appName = appName;
}
public String getAppName() {
return this.appName;
}
}
验证方法:
public String validateForNull(MyClass myclass) {
String name = myclass.getAppName();
if(name == null || name.isEmpty()) {
return //here I want to return attributeName which will be "appName"
}
}
我意识到返回表示属性名称的常量字符串对于该方法来说会更加简单和简洁。但我想知道是否可以将其作为通用方法来执行,其中 validate 方法采用类对象并检查所有/指定属性是否为 null/空,并在 null/空值的情况下返回属性名称。
谢谢
最佳答案
您无法通过调用 getter 或 setter 来获取属性的名称。
顺便说一句,您不能保证您调用的方法只是设置或返回一个简单的属性。
但是你是对的,你可以通过反射来获取给定对象的属性值。
public String validateForNull(MyClass myclass) throws IllegalArgumentException, IllegalAccessException {
// Get the attributes of the class
Field[] fs = myclass.getClass().getFields();
for(Field f : fs) {
// make the attribute accessible if it's a private one
f.setAccessible(true);
// Get the value of the attibute of the instance received as parameter
Object value = f.get(myclass);
if(value == null) {
return f.getName();
}
}
return null;
}
做这样的事情将需要比 if(value == null) 更完整的测试,因为我想您可以拥有多种类型的属性,并且每种类型都有特定的验证。
如果您决定采用这种方式,您可以使用注释来标识要验证的属性和用途:
Annotation[] ans = f.getAnnotations();
检查属性上是否存在您的注释,从而仅验证必填字段
关于Java-调用get方法时获取类属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47927756/