public class reflectDemo { public static void main(String[] args) throws Exception { Scanner in = new Scanner(System.in);//-------------------------提醒用户输入 System.out.println("请输入类名(全路径:package.className)"); String cname=in.nextLine(); System.out.println("属性名"); String fname=in.nextLine(); Class cla = Class.forName(cname);//----------------------------动态加载类 Field fil = cla.getDeclaredField(fname);//---------------------动态获取属性 Object obj = cla.newInstance();//------------------------------动态创建对象 Object val = fil.get(obj);//-----------------------------------获取查询属性的值 System.out.println("查询的属性值为:"+val);//--------------------控制台打印 } }
来源:https://www.cnblogs.com/Peter-Yu/p/9108778.html