私有成员变量 值没输出 即代码不进if中的else if
来源:2-9 自由编程
_谁会观星
2020-12-28 14:46:14
# 具体遇到的问题
# 报错信息的截图
# 相关课程内容截图
# 尝试过的解决思路和结果
# 粘贴全部相关代码,切记添加代码注释(请勿截图)
package com.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class ReflectTest {
public static void main(String[] args) {
try {
Class bookClass = Class.forName("com.reflect.Book");
Constructor constructor = bookClass.getConstructor(new Class[]{
Integer.class, String.class, Float.class
});
Book book = (Book) constructor.newInstance(new Object[]{
1001, "Java", 33.3F
});
Field[] fields = bookClass.getFields();
for (Field field:fields){
if (field.getModifiers() == 1){
//public
Object val = field.get(book);
System.out.println(field.getName()+":"+val);
}else if(field.getModifiers() == 2){
//private
String methodName = "get"+field.getName().substring(0,1).toUpperCase()
+field.getName().substring(1);
Method getMethod = bookClass.getMethod(methodName);
Object rtn = getMethod.invoke(book);
System.out.println(field.getName()+":"+ rtn);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
}
1回答
好帮手慕阿满
2020-12-28
同学你好,获取属性时,应该使用getDeclaredFields(),而不是getFields(),如:
getFields()是获取public修饰的属性,如果是私有的 ,getFields()获取不到,也就不执行else if中的代码。
祝学习愉快~
相似问题