
正文
newInstance() 的参数版本与无参数版本
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
通过反射创建新的类示例,有两种方式:
Class.newInstance()
Constructor.newInstance()
以下对两种调用方式给以比较说明:
Class.newInstance() 只能够调用无参的构造函数,即默认的构造函数;
Constructor.newInstance() 可以根据传入的参数,调用任意构造构造函数。
Class.newInstance() 要求被调用的构造函数是可见的,也即必须是public类型的;
Constructor.newInstance() 在特定的情况下,可以调用私有的构造函数,需要通过setAccessible(true)实现。
下面是两种方式:
package com.reflect;
import java.lang.reflect.Constructor;class TestB
{
public TestB()
{
System.out.println("Test A");
}
//设置构造方法私有
private TestB(int a,String b)
{
System.out.println("Test parames");
}
}
public class Test { public static void main(String []args) throws Exception
{
Test b=new Test();
Class c=Class.forName("com.reflect.TestB");
//无参数
TestB b1=(TestB) c.newInstance();
//有参数需要使用Constructor类对象
//这种方式和下面这种方式都行,注意这里的参数类型是 new Class[]
//Constructor ct=c.getDeclaredConstructor(int.class,String.class);
Constructor ct=c.getDeclaredConstructor(new Class[]{int.class,String.class});
ct.setAccessible(true);
//这种方式和下面这种方式都可以:注意这里的参数类型是 new Object[]
//TestB b2=(TestB) ct.newInstance(1,"2");
TestB b2=(TestB) ct.newInstance(new Object[] {1,"2"});
}
}
运行结果:
Test A
Test parames






