简体   繁体   中英

How to dynamically create an instance in java, from string with parameters?

I know this question is answered some time. But all the time the parameter is an object. Thats what I want to replace:

if (s.equals("A")) { add (obj = new A(x,y)); }
if (s.equals("B")) { add (obj = new B(x,y)); }
if (s.equals("C")) { add (obj = new C(x,y)); }

I have this:

try
{
    Class cl = Class.forName(s);
    Constructor con = cl.getConstructor (x, y);
    obj = con.newInstance(x, y);
}

but it expect x,y as a class, but its an int. How to do this>

You need

cl.getConstructor(int.class, int.class);

There are Class objects reflecting on primitive types, and even the void type has it reflective counterpart in Void.class .

You need to use:

cl.getConstructor(int.class,int.class);

to get the constructor with (int,int) arguments.

If x and y are int , try to call getConstructor by passing the type of the exptected parameters:

Class cl = Class.forName(s);
Constructor con = cl.getConstructor (Integer.TYPE, Integer.TYPE);
obj = con.newInstance(x, y);

What you need is to provide the types to the getConstructor method. That is

Constructor con = cl.getConstructor (x.getClass(), y.getClass());

or

 Constructor con = cl.getConstructor (ClassOfX.class, ClassOfY.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM