概述
package com.itheima.myreffect3;
import java.lang.reflect.Field;
public class RefectDemo2 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
//method1();
method2();
}
private static void method2() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
Class clazz = Class.forName("com.itheima.myreffect3.Student");
Field field = clazz.getDeclaredField("money");
field.setAccessible(true);
Student student = (Student) clazz.newInstance();
Object o = field.get(student);
System.out.println(o);
}
private static void method1() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
Class clazz = Class.forName("com.itheima.myreffect3.Student");
Field field = clazz.getField("name");
Student stuent = (Student) clazz.newInstance();
field.set(stuent,"zhangsan");
System.out.println(stuent);
}
}
package com.itheima.myreffect3;
public class Student {
public String name;
public int age;
public String gernder;
private int money=300;
@Override
public String toString() {
return "Student{" +
"name='" + name + ''' +
", age=" + age +
", gernder='" + gernder + ''' +
", money=" + money +
'}';
}
}
最后
以上就是高贵灯泡为你收集整理的154.-反射-利用Field赋值和获取值__的全部内容,希望文章能够帮你解决154.-反射-利用Field赋值和获取值__所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复