我们先创建了一个Person类
package reflect;
public class Person {
public String name = "zhangsan";
public Person(){
System.out.println("person");
}
public Person(String name){
System.out.println(name);
}
public Person(String name,int password){
System.out.println("person name and password");
}
private Person(int i){
System.out.println("person list");
}
}
加载类的方法
package reflect;
public class Demo {
public static void main(String[] args) throws ClassNotFoundException {
/*
* 反射:加载类,获取类的字节码
*/
//方法一
Class clazz = Class.forName("reflect.Person");
//方法二
Class clazz2 = new Person().getClass();
//方法三
Class clazz3 = Person.class;
}
}
反射类的构造函数,可访问Person类,@Test是用junit来测试是否实现的
package reflect;
import java.awt.List;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
import org.junit.Test;
public class Demo2 {
@Test
public void test() throws ClassNotFoundException, ReflectiveOperationException, SecurityException{
Class clazz = Class.forName("reflect.Person");
Constructor c = clazz.getConstructor(null);
Person p = (Person) c.newInstance(null);
System.out.println(p.name);
}
@Test
public void test2() throws Exception{
Class clazz = Class.forName("reflect.Person");
Constructor c = clazz.getConstructor(String.class);
Person p = (Person) c.newInstance("success");
System.out.println(p.name);
}
//访问私有
@Test
public void test3() throws Exception{
Class clazz = Class.forName("reflect.Person");
Constructor c = clazz.getDeclaredConstructor(int.class);
c.setAccessible(true);
Person p = (Person) c.newInstance(13);
System.out.println(p.name);
}
//创建对象的另外一种方式
@Test
public void test4() throws Exception{
Class clazz = Class.forName("reflect.Person");
Person p = (Person) clazz.newInstance();
System.out.println(p);
}
}