1、Class类是什么样的类?
(1)Class类是用来描述类的类,Class类中封装了获取类的属性、方法、构造器的方法。
(2)Class类是由JVM生成的。
2、怎么得到Class类?
package myProject; public class Person { private int age; private String name; public Person() { System.out.println("无参构造方法"); } public Person(String name) { this.name=name; System.out.println("有参构造方法"); } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
package myProject; public class ReflectionTest { public static void main(String[] args) throws ClassNotFoundException { Class clazz=null; //1、类名.class clazz=Person.class; System.out.println(clazz); //2、对象名.getClass() Object obj=new Person(); clazz=obj.getClass(); System.out.println(clazz); //3、Class.forName(全类名) clazz=Class.forName("myProject.Person"); System.out.println(clazz); } }
3、什么是反射?
java反射机制是
1) 在运行时通过访问构造方法,构造任意一个类的对象
2)在运行时访问任意对象的属性、方法。
public class ReflectPo { private String a; private int b; public ReflectPo(){ } public ReflectPo(String a,Integer b){ this.a=a; this.b=b; } public String getA(){ return a; } private int getB(){ return b; } public void setAB(String a,int b){ System.out.println("a is "+a+"; b is "+b); } @Override public String toString(){ return "{a:"+a+";b:"+b+"}"; } }
public class Test { public static void main(String[] args)throws Exception{ //1、通过访问构造函数,在运行时创建对象 //(1)访问无参构造函数 Class clazz1=ReflectPo.class; Constructor constructor=clazz1.getDeclaredConstructor(); ReflectPo reflectPo=(ReflectPo) constructor.newInstance(); System.out.println(reflectPo.toString()); //(2)访问有参构造函数 Class clazz2=ReflectPo.class; Constructor constructor2=clazz2.getDeclaredConstructor(String.class,Integer.class); ReflectPo reflectPo2=(ReflectPo) constructor2.newInstance("BONNIE",1); System.out.println(reflectPo2.toString()); //2、访问属性 //(1)给属性赋值 Class clazz3=ReflectPo.class; Field field=clazz3.getDeclaredField("a"); field.setAccessible(true); Object object=clazz3.newInstance(); field.set(object,"Bonnie"); System.out.println(object.toString()); //(2)获取属性的值 System.out.println(field.get(object)); //3、访问方法 //(1)访问公有方法 ReflectPo reflectPo3=new ReflectPo("bb",2); Class clazz=reflectPo3.getClass(); Method method=clazz.getDeclaredMethod("getA"); System.out.println(method.invoke(reflectPo3)); //(2)访问私有方法 Method method2=clazz.getDeclaredMethod("getB"); method2.setAccessible(true); System.out.println(method2.invoke(reflectPo3)); //(3)访问带参方法 Method method3=clazz.getDeclaredMethod("setAB", String.class, int.class); method3.invoke(reflectPo3,"uu",9); } }