任何人都可以澄清一下,如果我在java中调用类的get / set方法时是否可以获得类属性名称。
我在网上看到了一些东西,可以使用反射概念来获取类属性名称。
我的情况:
尝试编写一种方法来检查属性值是否为空/空,并在属性值为空/空的情况下返回属性名称。
例:
类:
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 / empty,并在出现null / empty值的情况下返回属性名称。
谢谢
最佳答案
您无法获取调用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();
要检查您的注释是否存在于属性上,从而仅验证必填字段