Java Reflection - Constructors

http://tutorials.jenkov.com/java-reflection/constructors.html


Using Java Reflection you can inspect the constructors of classes and instantiate objects at runtime. This is done via the Java class java.lang.reflect.Constructor. This text will get into more detail about the JavaConstructor object.

Obtaining Constructor Objects

The Constructor class is obtained from the Class object. Here is an example:

Class aClass = ...//obtain class object
Constructor[] constructors = aClass.getConstructors();

The Constructor[] array will have one Constructor instance for each public constructor declared in the class.

If you know the precise parameter types of the constructor you want to access, you can do so rather than obtain the array all constructors. This example returns the public constructor of the given class which takes a Stringas parameter:

Class aClass = ...//obtain class object
Constructor constructor =
        aClass.getConstructor(new Class[]{String.class});

If no constructor matches the given constructor arguments, in this case String.class, aNoSuchMethodException is thrown.

Constructor Parameters

You can read what parameters a given constructor takes like this:

Constructor constructor = ... // obtain constructor - see above
Class[] parameterTypes = constructor.getParameterTypes();

Instantiating Objects using Constructor Object

You can instantiate an object like this:

//get constructor that takes a String as argument
Constructor constructor = MyObject.class.getConstructor(String.class);

MyObject myObject = (MyObject)
        constructor.newInstance("constructor-arg1");

The Constructor.newInstance() method takes an optional amount of parameters, but you must supply exactly one parameter per argument in the constructor you are invoking. In this case it was a constructor taking a String, so one String must be supplied.



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值