什么是反射
解析Java类中的各个组成部分映射成一个个java对象。
为什么用反射
多用于框架和组件,写出复用性高的通用程序。
Class类
Class代表的就是字节码文件。获取方式
1、类名.class
2、对象.getClass()
3、Class.forName
开发中建议使用第三种,这种方式耦合度低,没有依赖性 。
package cn.itcast.reflect;
import org.junit.Test;
public class Demo1 {
//获取Class对象
@Test
public void demo2() throws ClassNotFoundException
{
Class clazz=Teacher.class;
Teacher t=new Teacher();
Class clazz1=t.getClass();
Class clazz2=Class.forName("cn.itcast.reflect.Teacher");
System.out.println(clazz);
System.out.println(clazz1);
System.out.println(clazz2);
}
}
class Teacher
{
private int id;
private double salary;
}
Constructor(构造器对象)
构造器的作用就是用来创建对象的,Constructor代表的是构造器对象,我们得到它之后就可以实例化对象了。
获取方式
getConstructor()
getConstructors()
package cn.itcast.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Ignore;
import org.junit.Test;
public class Demo1 {
@Test
public void demo3() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException
{
//1、得到Teacher类的Class对象
Class clazz=Teacher.class;
//2、得到Teacher类的构造器
Constructor c1=clazz.getConstructor();
Constructor c2=clazz.getConstructor(String.class);
Constructor c3=clazz.getConstructor(String.class,int.class);
//3、通过Constructor对象创建Teacher类的实例
Teacher obj1=(Teacher)c1.newInstance();//相当于new Teacher();
obj1.show();
Teacher obj2=(Teacher)c2.newInstance("张三");//相当于new Teacher("张三");
obj2.show();
Teacher obj3=(Teacher)c3.newInstance("Steve",20);//相当于new Teacher("Steve",20);
obj3.show();
}
}
class Teacher
{
public String name="Jack";
public int age=30;
public Teacher()
{
System.out.println("Teacher的无参构造方法!");
}
public Teacher(String name)
{
this.name=name;
System.out.println("Teacher的有参构造方法1!");
}
public Teacher(String name,int age)
{
this.name=name;
this.age=age;
System.out.println("Teacher的有参构造方法2!");
}
public void show() {
System.out.println("name=" + name + " age=" + age);
}
}
注意:关于Constructor的注意事项
1、如果构造方法不是public。那么要获取其构造器对象使用,可以用getDeclaredConstructor()方法。
2、对于私有化权限,在使用前必须设置权限检查。
3、在开发中,我们在得到Class时,一般会直接实例化类的对象。
package cn.itcast.reflect;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import org.junit.Ignore;
import org.junit.Test;
public class Demo1 {
@Test
public void demo4() throws SecurityException, NoSuchMethodException, IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException
{
//1、获取Teacher类的Class对象
Class clazz=Teacher.class;
//2、获取非public的构造器对象
Constructor c=clazz.getDeclaredConstructor(String.class,int.class);
//3、取消java安全检查
c.setAccessible(true);
//4、创建Teacher对象
Teacher obj=(Teacher)c.newInstance("李思思",19);
obj.show();
}
}
class Teacher
{
public String name="Jack";
public int age=30;
private Teacher(String name,int age)
{
this.name=name;
this.age=age;
System.out.println("Teacher的有参构造方法2!");
}
public void show() {
System.out.println("name=" + name + " age=" + age);
}
}
由以上可知利用反射可以创建对象。