且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用接受字符串参数的构造函数实例化一个类对象?

更新时间:2023-11-02 19:23:46

Class.newInstance 调用无参数构造函数(不带任何参数的构造函数).为了调用不同的构造函数,您需要使用反射包(java.lang.reflect).

Class.newInstance invokes the no-arg constructor (the one that doesn't take any parameters). In order to invoke a different constructor, you need to use the reflection package (java.lang.reflect).

像这样获取一个 Constructor 实例:

Get a Constructor instance like this:

Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);

getConstructor 的调用指定您需要采用单个 String 参数的构造函数.现在创建一个实例:

The call to getConstructor specifies that you want the constructor that takes a single String parameter. Now to create an instance:

Object o = cons.newInstance("JLabel");

大功告成.

附言仅将反射作为最后的手段!

P.S. Only use reflection as a last resort!