对反射的学习

反射就是加载类,并解剖出各个类的组成部分。
比如:你的路径是cn.csdn.reflector.Student 那么,你想当你想获得某个类的描述信息创建这个实例时,可以调用反射机制.就不用Student student=new Student();而是Student student=Class.forName("cn.csdn.reflector.Student");这样就可以产生该类的实例了。
加载类还有两种方法:(如下)(Student为你获得信息的类)1.使用Object类的getClass()方法  Student student;  Class c=student.getClass();2.使用"类名.class"的方式  Class c=Student.class;
Public  Constructor  getConstructor(Class<?>... parameterTypes)
方法用于从类中解剖出构造函数、方法和成员变量(属性)。
无参的构造器解析:
// public Student()
@Test
public void test1() throws ClassNotFoundException, SecurityException,
NoSuchMethodException, IllegalArgumentException,
InstantiationException, IllegalAccessException,
InvocationTargetException {
// 1加载类
Class cls = Class.forName("cn.csdn.reflect.Student");
// 2通过无参数的构造器解析
Constructor constructor = cls.getConstructor(null);
// 3创建类的实例
Student entity = (Student) constructor.newInstance(null);
        //4调用对象的方法
entity.study();
       }
       }
有参的构造器解析:public Student(String name,int age);
@Test
public void test2()throws Exception{
//1加载类
Class cls = Class.forName("cn.csdn.reflect.Student");
//2通过带有参数的构造器解析  
       //String.class是获取构造器的参数类型
Constructor constructor = cls.getConstructor(String.class,int.class);
//3创建类实例
Student entity = (Student)constructor.newInstance("redarmy",90);
//4调用方法
entity.study();
System.out.println(entity.getName());
}

如果这个class是在程序运行中由用户动态添加的,你不会知道这个类的构造方法是什么,也许只知道类的存放位置,那么java就必须在运行过程中对代码进行分析和调用。这就要用到reflector。
//@Test
public void test3()throws Exception{
//1加载类
Class cls = Class.forName("cn.csdn.reflect.Student");
//2获取加载类中的所有的构造器
Constructor csr[] = cls.getConstructors();
//3、遍历构造器csr
for(Constructor c:csr){
//打印出构造器参数的类型及构造器名称
System.out.println(c.toGenericString());

      }

      }

//解析:public cn.csdn.reflect.Student(java.lang.String[])
@Test
public void test4()throws Exception{
//1加载类
Class cls = Class.forName("cn.csdn.reflect.Student");
//2根据构造器参数类型获取相应的构造器对象   
Constructor csr = cls.getConstructor(String[].class);
String str[]={"111","123"};
//3创建实体对象
Student entity = (Student)csr.newInstance((Object)str);
//4调用方法
entity.study();
}

//解析私有构造方法
@Test
public void test5()throws Exception{
//1加载类
Class cls = Class.forName("cn.csdn.reflect.Student");
//2根据构造器参数类型获取相应的构造器对象   
Constructor csr = cls.getDeclaredConstructor(List.class);
csr.setAccessible(true);//暴力
//3、创建实体对象
Student entity = (Student)csr.newInstance(new ArrayList());

//4调用方法
entity.study();
}
   }

你可能感兴趣的:(C++,c,C#)