- class Cat{
- private String name;
- public int age;
- private String color;
- }
- class test5{
- public static void main(String[] args) throws Exception{
- Class clazz = Cat.class;
- Field field = clazz.getDeclaredField("name");
- Cat c = (Cat)clazz.newInstance();
- field.setAccessible(true);
- field.set(c,"youxiang");
- String name = (String)field.get(c);
- System.out.println(name);
- Field f = clazz.getField("age");
- field.setInt(c,21);
- int i = field.getInt(c);
- System.out.println(i);
- }
- }
复制代码 第一个反射name没问题 第二个反射age报错 类型错误 我晕了...........
|