反这类的构造函数(写框架时才会用到反射类)


package reflet;

import java.util.List;

public class person {
    public String name="hahaah";
    public person()//无参构造函数
    {
        System.out.println("person");
    }
    public person(String name)//有参构造函数
    {
        System.out.println(name);
    }
    public person(String name,int password)//有参构造函数
    {
        System.out.println(name+":"+password);
    }
    private person(List list)//有参构造函数
    {
        System.out.println("person list");
    }

 


package
reflet; import java.lang.reflect.Constructor; import java.util.ArrayList; import java.util.List; import org.junit.Test; //反射类的构造函数,创建类的对象 public class demo { //反射构造函数:public person @Test public void test1() throws Exception { Class clazz=Class.forName("reflet.person");//加载类 Constructor c=clazz.getConstructor(null); person p=(person)c.newInstance(null); System.out.println(p.name); } //反射构造函数:public person(String name) @Test public void test2() throws Exception { Class clazz=Class.forName("reflet.person"); Constructor c=clazz.getConstructor(String.class); person p=(person)c.newInstance("sdqawjuhugbyugdr"); System.out.println(p.name); } //反射构造函数:public person(String name,int password) @Test public void test3() throws Exception { Class clazz=Class.forName("reflet.person"); Constructor c=clazz.getConstructor(String.class,int.class); person p=(person)c.newInstance("sdqawjuhugbyugdr",45); System.out.println(p.name); } //反射构造函数:private person(List list) @Test public void test4() throws Exception { Class clazz=Class.forName("reflet.person"); Constructor c=clazz.getDeclaredConstructor(List.class);//因为此函数是private类型,所以用getDeclaredConstructor c.setAccessible(true);//暴力反射(作用是让私有可以被外界访问) person p=(person)c.newInstance(new ArrayList()); System.out.println(p.name); } //创建对象的另外一种途径:以下test5等效于test1 @Test public void test5() throws Exception { Class clazz=Class.forName("reflet.person"); person p=(person) clazz.newInstance(); System.out.println(p.name); } }

 

posted on 2015-01-25 19:31  曾经的码农  阅读(142)  评论(0编辑  收藏  举报