Can I use Class.newInstance() with constructor arguments?
I would like to use Class.newInstance()
but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?
Asked by: Michelle568 | Posted: 28-01-2022
Answer 1
MyClass.class.getDeclaredConstructor(String.class).newInstance("HERESMYARG");
or
obj.getClass().getDeclaredConstructor(String.class).newInstance("HERESMYARG");
Answered by: Kellan974 | Posted: 01-03-2022
Answer 2
myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);
Edit: according to the comments seems like pointing class and method names is not enough for some users. For more info take a look at the documentation for getting constuctor and invoking it.
Answered by: Adrian669 | Posted: 01-03-2022Answer 3
Assuming you have the following constructor
class MyClass {
public MyClass(Long l, String s, int i) {
}
}
You will need to show you intend to use this constructor like so:
Class classToLoad = MyClass.class;
Class[] cArg = new Class[3]; //Our constructor has 3 arguments
cArg[0] = Long.class; //First argument is of *object* type Long
cArg[1] = String.class; //Second argument is of *object* type String
cArg[2] = int.class; //Third argument is of *primitive* type int
Long l = new Long(88);
String s = "text";
int i = 5;
classToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);
Answered by: Kellan302 | Posted: 01-03-2022
Answer 4
Do not use Class.newInstance()
; see this thread: Why is Class.newInstance() evil?
Like other answers say, use Constructor.newInstance()
instead.
Answer 5
You can get other constructors with getConstructor(...).
Answered by: Elise657 | Posted: 01-03-2022Answer 6
Follow below steps to call parameterized consturctor.
- Get
Constructor
with parameter types by passing types inClass[]
forgetDeclaredConstructor
method ofClass
- Create constructor instance by passing values in
Object[]
for
newInstance
method ofConstructor
Example code:
import java.lang.reflect.*;
class NewInstanceWithReflection{
public NewInstanceWithReflection(){
System.out.println("Default constructor");
}
public NewInstanceWithReflection( String a){
System.out.println("Constructor :String => "+a);
}
public static void main(String args[]) throws Exception {
NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName("NewInstanceWithReflection").newInstance();
Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});
NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{"StackOverFlow"});
}
}
output:
java NewInstanceWithReflection
Default constructor
Constructor :String => StackOverFlow
Answered by: Kimberly468 | Posted: 01-03-2022
Answer 7
You can use the getDeclaredConstructor
method of Class. It expects an array of classes. Here is a tested and working example:
public static JFrame createJFrame(Class c, String name, Component parentComponent)
{
try
{
JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance("name");
if (parentComponent != null)
{
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
else
{
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
}
frame.setLocationRelativeTo(parentComponent);
frame.pack();
frame.setVisible(true);
}
catch (InstantiationException instantiationException)
{
ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());
}
catch(NoSuchMethodException noSuchMethodException)
{
//ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, "NamedConstructor");
ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), "(Constructor or a JFrame method)");
}
catch (IllegalAccessException illegalAccessException)
{
ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));
}
catch (InvocationTargetException invocationTargetException)
{
ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));
}
finally
{
return null;
}
}
Answered by: Ada145 | Posted: 01-03-2022
Answer 8
I think this is exactly what you want http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html
Although it seems a dead thread, someone might find it useful
Answered by: Charlie194 | Posted: 01-03-2022Similar questions
java - What is the difference between the new operator and Class.newInstance()?
What is the difference between new operator and Class.forName(...).newInstance()? Both of them create instances of a class, and I'm not sure what the difference is between them.
java - Class.newInstance() how to use a method?
I created an abstract class as follows:
abstract class Chance
{
public void setTeams(SportEvent aSportEvent)
{
firstTeam = aSportEvent.getFirstTeam();
secondTeam = aSportEvent.getSecondTeam();
}
private int totalPlayedGames()
{
int playedAtHome = firstTeam.getHomePlayedGames();
int playedAway = secondTeam.getAwayPlayedGames();
...
multithreading - for Java, is Class.newInstance() thread safe
a part of code like this:
class Test {
private static final Map<String, Class> urlHandlers = new ConcurrentHashMap<String, Class>();
static {
urlHandlers.put(urlRegexA, HandlerA.class);
urlHandlers.put(urlRegexB, HandlerB.class);
...
}
public Handler handle(String url) {
......
if(url match urlRegex) {
Class claz = urlHandlers.get(urlRegex);
//in multi-thread...
jakarta ee - tmpConstructor empty in Java Class.newInstance()
I have tracked down an error to line 362 of the java.lang.Class class:
Constructor<T> tmpConstructor = cachedConstructor;
The variable does not seem to get assigned. In the debug expression windows it only says "tmpConstructor cannot be resolved to a variable". The cachedConstructor is not null.
An error is only thrown further down when a the newInstance() function is called:...
java - Can't instantiate class no empty constructor when calling Class.newInstance()
I'm trying to create a RadioGroup in my custom Dialog class using the following bit of code:
public static Dialog singleChoiceRB(
Activity a
, String title
, CharSequence[] items
, Class<?> itemListener
, OnClickListener pocl
, String pocl_txt){
MyCustomDialog dialog = MyCustomDialog();
// Setup stuff in here //
RadioGroup rg = new RadioGroup(a);
for(int i = 0; ...
java - What to use instead of Class.newInstance()?
Class.newInstance() is marked deprecated. Documentation does not suggest any alternatives. How are we meant to create instances now?
Still can't find your answer? Check out these amazing Java communities for help...
Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)