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
).
Get a Constructor
instance like this:
Class<?> cl = Class.forName("javax.swing.JLabel");
Constructor<?> cons = cl.getConstructor(String.class);
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");
And you're done.
P.S. Only use reflection as a last resort!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…