`
seahb
  • 浏览: 69134 次
  • 性别: Icon_minigender_1
  • 来自: 0
文章分类
社区版块
存档分类
最新评论

class.newInstance和constructor.newInstance 区别

阅读更多

通过反射创建新的类示例,有两种方式:
Class.newInstance()
Constructor.newInstance()


以下对两种调用方式给以比较说明:
Class.newInstance() 只能够调用无参的构造函数,即默认的构造函数;
Constructor.newInstance() 可以根据传入的参数,调用任意构造构造函数。

Class.newInstance() 抛出所有由被调用构造函数抛出的异常。

Class.newInstance() 要求被调用的构造函数是可见的,也即必须是public类型的;
Constructor.newInstance() 在特定的情况下,可以调用私有的构造函数。


Class A(被调用的示例):
public class A {
private A(){
System.out.println("A's constructor is called.");
}
private A(int a,int b){
System.out.println("a:"+a+" b:"+b);
}
}

Class B(调用者):
import java.lang.reflect.Constructor;
import static java.lang.System.out;
public class B {
public static void main(String[] args) {
B b=new B();
out.println("通过Class.NewInstance()调用私有构造函数:");
b.newInstanceByClassNewInstance();
out.println("通过Constructor.newInstance()调用私有构造函数:");
b.newInstanceByConstructorNewInstance();
}
/*通过Class.NewInstance()创建新的类示例*/
private void newInstanceByClassNewInstance(){
try {/*当前包名为reflect,必须使用全路径*/
A a=(A)Class.forName("reflect.A").newInstance();
} catch (Exception e) {
out.println("通过Class.NewInstance()调用私有构造函数【失败】");
}
}

/*通过Constructor.newInstance()创建新的类示例*/
private void newInstanceByConstructorNewInstance(){
try {/*可以使用相对路径,同一个包中可以不用带包路径*/
Class c=Class.forName("A");
/*以下调用无参的、私有构造函数*/
Constructor c0=c.getDeclaredConstructor();
c0.setAccessible(true);
A a0=(A)c0.newInstance();
/*以下调用带参的、私有构造函数*/
Constructor c1=c.getDeclaredConstructor(new Class[]{int.class,int.class});
c1.setAccessible(true);
A a1=(A)c1.newInstance(new Object[]{5,6});
} catch (Exception e) {
e.printStackTrace();
}
}

}

输入结果如下:
通过Class.NewInstance()调用私有构造函数:
通过Class.NewInstance()调用私有构造函数【失败】
通过Constructor.newInstance()调用私有构造函数:
A's constructor is called.
a:5 b:6

说明方法newInstanceByClassNewInstance调用失败,而方法newInstanceByConstructorNewInstance则调用成功。
如果被调用的类的构造函数为默认的构造函数,采用Class.newInstance()则是比较好的选择,
一句代码就OK;如果是老百姓调用被调用的类带参构造函数、私有构造函数,
就需要采用Constractor.newInstance(),两种情况视使用情况而定。
不过Java Totorial中推荐采用Constractor.newInstance()。

本文来自CSDN博客:http://blog.csdn.net/fenglibing/archive/2009/09/08/4531033.aspx

分享到:
评论
1 楼 Miss_understand 2016-06-25  
不看标签我还以为是讲java的呢

相关推荐

    Oracle命令大全

    Object userDao = userDaoClass.newInstance(); Class userServiceClass = Class.forName(config .getInitParameter("userService")); Constructor cons1 = userServiceClass.getConstructor(UserDao...

    richfaces_erro

    richfaces_erro 正在建立中 调试当中 严重: Cant instantiate class: org.ajax4jsf.application.AjaxStateManager. java.lang.reflect.... at java.lang.reflect.Constructor.newInstance(Constructor.java:494)

    java反序列化漏洞URLClassLoader利用1

    执行链实际为:URLClassLoader.class.getConstructor(java.net.URL[].class).newInstance(new

    java 反射简单用例

    java反射的用例代码 // //获取类对象的属性 // Field field = clazz.getDeclaredField("name");...// Object instance = constructor.newInstance(new Object[]{1, "李四", "中国"}); // System.out.println(instance);

    Java 反射(Reflection) 经典实用例子

    public Object newInstance(String className, Object[] args) throws Exception { Class newoneClass = Class.forName(className); Class[] argsClass = new Class[args.length]; for (int i = 0, j = ...

    Java 高级特性.doc

    String str = (String)constructor.newInstance(new StringBuffer("abc")); System.out.println(str); class.newInstance()内部其实就是在用默认的构造方法 ----------------------- 讲Method //方法 Method ...

    day021-反射和注解笔记和代码.rar

    Object newInstance = constructor.newInstance("某文"); //获取private修饰的方法:testPrivate Method method2 = clazz.getDeclaredMethod("testPrivate"); method2.setAccessible(true);/...

    JAVA核心知识点整理(有效)

    25 3:ServicorTo 和 ServicorFrom 互换................................................................................................................25 2.3.3.1. 2.4.1. 如何确定垃圾 ......................

    Thinking in Java 4th Edition

    instance initialization ................ 132 Array initialization ............. 133 Variable argument lists ............. 137 Enumerated types ............... 141 Summary ............................ ...

    abstractproduct_0_2.tar.gz_inheritance

    abstractproduct.h is C++ template-based library providing reflective object creation mechanism (similar to Java s Class.forName("ClassNameHere").newInstance()). It does so by static initialization of ...

    java反射配置文件实现

    Object obj=c.newInstance(); // 创建实例, 生成对象; Constructor con=c.getDeclaredConstructor(String.class,int.class); // 反映此 Class 对象所表示的类或接口的指定构造方法。 /* 跟 Student类中的两个参数...

    spring-framework-reference4.1.4

    Instantiation using an instance factory method ........................................... 30 4.4. Dependencies ...........................................................................................

    spring-framework-reference-4.1.2

    Instantiation using an instance factory method ........................................... 30 4.4. Dependencies ...........................................................................................

    Class.js:在JS中实现类和继承

    //Create a new class var ClassA = Class . create ( { //constructor init : function ( value ) { //"this" can directly be used this . value = value ; } , //instance method print : fuction ( ) { ...

    servlet2.4doc

    GenericServlet() - Constructor for class javax.servlet.GenericServlet Does nothing. getAttribute(String) - Method in interface javax.servlet.ServletContext Returns the servlet container attribute ...

    perl对象经典例题

    This example demonstrates how to a base class (or super class) inherited instance variables, and the instance variables to the new object in the method for their own constructor calls the base class.

    Java自定义异常案例--ExceptionManager(java源码)

    * Constructs a new instance with the specified detail message and cause. The * concrete handler is its super class. This constructor always used to construct * an exception wrapping the exist ...

    文件加密解密算法(Java源码)

    KeySpec dks = (KeySpec) constructor.newInstance(new Object[]{rawKeyData}); // 创建一个密钥工厂,然后用它把DESKeySpec转换成SecretKey对象 SecretKeyFactory keyFactory = SecretKeyFactory.getInstance...

    CyAPI说明文档

    To use the library you must create an instance of the CCyUSBDevice class using the new keyword. A CCyUSBDevice object knows how many USB devices are attached to the CyUsb3.sys driver and can be made ...

    Cypress CyAPI Programmer's Reference

    create an instance of the CCyUSBDevice class using the new keyword. A CCyUSBDevice object knows how many USB devices are attached to the CyUsb.sys driver and can be made to abstract any one of those ...

Global site tag (gtag.js) - Google Analytics