0

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>

2
  • if you know that x,y are ints then maybe try cl.getConstructor (int.class, int.class); Commented Jun 3, 2013 at 12:40
  • autobox primitive values to wrapper classes Constructor con = c1.getConstructor((Integer) x, (Integer) y); Commented Jun 3, 2013 at 12:41

4 Answers 4

5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

may I ask more? It say "java.lang.ClassNotFoundException: A" but if I directly instantize that class A, it does work.
You must give the fully qualified class name to the reflective call.
1

You need to use:

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

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

Comments

1

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.