-1

A method takes a class cls as parameter and I need to instantiate a cls object. Something as follows:

private void foo(Class<?> cls){
  cls bar = new cls();
  ...
}

For example, let's say cls is Integer.class (but solution should work for any class). How can I instantiate an Integer inside that method?

Niccolò
  • 2,135
  • 3
  • 24
  • 36

4 Answers4

1

You could check the type and create a new integer:

if(cls == Integer.class) return Integer.valueOf(0);

or

if(cls == Integer.class) {
    return cls.getConstructor(int.class).newInstance(0);
}

However this method would still return an object, not an instance of Integer.

A better option could be something like:

static <T extends Number> T newNumber1(Class<T> tClass, String s){
    if(tClass == Integer.class){
        return (T) Integer.valueOf(s);
    }
}

// OR

static Number newNumber2(Class<? extends Number> tClass, String s){
    if(tClass == Integer.class){
        return Integer.valueOf(s);
    }
}

Usage:

int v1 = newNumber1(Integer.class, "5");
int v2 = newNumber2(Integer.class, "6").intValue();

UPDATE:

static <T> T newInstance(Class<T> tClass, String s) throws Exception{
    return tClass.getConstructor(String.class).newInstance(s);
}

public static void main(String[] args) throws Exception{
    Double d = newInstance(Double.class, "4");
    System.out.println(d);
}
Andrey Chaschev
  • 15,055
  • 5
  • 43
  • 63
  • I edited the OP, it should be more clear now. – Niccolò Jan 13 '14 at 17:45
  • @Niccolò My answer is for the method signature you added, except that your method is `void`. What does not work for you? – Andrey Chaschev Jan 13 '14 at 17:50
  • I would avoid the explicit use of 'Integer' in the method code. To me worked fine to change the signature from foo(Class> cls) to foo(Class cls) and then T bar=cls.getConstructor(String.class).newInstance(something). After all, that will work with basic types (String, Integer, Double ...) – Niccolò Jan 13 '14 at 18:01
  • So you need only the `String.class` constructor? I've added an example for this case. In case you need other constructors, you might want to check the type of the input class. – Andrey Chaschev Jan 13 '14 at 18:29
  • Yes, in my case the String constructor is all I need, after all it works for most of the class representing the basic types. Also my emphasis was more on the use of newInstance, getConstructor and on what to call them and how to return the correct type. Btw, you don't really need to cast the object to tClass as the object has been created by tClass constructor (do you?) – Niccolò Jan 13 '14 at 21:21
  • Yes, you are right - the cast is not needed. – Andrey Chaschev Jan 14 '14 at 09:27
1

Since Integer class doesn't have a 0-arg constructor, you can't directly use Class#newInstance() method here.

Rather, you can get the appropriate constructor, taking String or int argument using Class#getConstructor() method. And then create instance using that:

Class<Integer> clazz = Integer.class;
Integer value = clazz.getConstructor(String.class).newInstance("5");
Rohit Jain
  • 195,192
  • 43
  • 369
  • 489
  • well, as I wrote the class is passed by as a parameter [ex. foo(Class> cls)], so I can't write the first line of your code. In your second line I need to substitute 'Integer' with the type given at runtime. But the compiler complains.. – Niccolò Jan 11 '14 at 19:11
  • Do you just want to do this for `Integer`? If yes, then why not change the parameter to `Class`. And why have that method in the first place. Please clarify your requirement. – Rohit Jain Jan 11 '14 at 19:13
  • I edited the question, it should be clearer now. As a matter of fact I already got to the solution starting from your current answer. Just instead of foo(Class> cls) I wrote foo(Class cls) and then I can use your second line of code as 'T bar=cls.getConstructor(String.class).newInstance(something)'. Would you like to improve your question to get accepted? – Niccolò Jan 11 '14 at 23:08
-1

I assume you're asking about the general case - how do I create an instance of whichever class was passed into such a method. Clearly, if you just mean "how do I create an Integer", then it's nothing to do with that method.

From the Javadoc for Class

public T newInstance()
          throws InstantiationException,
                 IllegalAccessException

Creates a new instance of the class represented by this Class object. The class is instantiated as if by a new expression with an empty argument list. The class is initialized if it has not already been initialized.

Obviously, this won't work for Integer, as there is no constructor for Integer with an empty parameter list.

Dawood ibn Kareem
  • 68,796
  • 13
  • 85
  • 101
  • Not sure why this is downvoted. – JB Nizet Jan 11 '14 at 18:36
  • `Integer` has no nullary constructor. – Brian Roach Jan 11 '14 at 18:36
  • Yeah, my fault for clicking "Submit" when I was partway through typing it. – Dawood ibn Kareem Jan 11 '14 at 18:38
  • Yeah, I mean, I don't mean to pick nits (especially since this is a poor Q in the first place) but the OP does say he wants to use `Integer`. It's unlikely the method is of any use period, of course, since with the wildcard you have no idea what the class is. – Brian Roach Jan 11 '14 at 18:42
  • I took that to be an example. Like if he had said "I want to write Hello World to the console", I would seriously doubt that he has an actual need to print the words "Hello World" - rather, he wants to know how to print any old text. Maybe I misunderstood the question, but I took it to mean "I've got a `Class>`, now how do I instantiate it in the general case". Which WOULD be a useful question, if he had asked it more clearly. – Dawood ibn Kareem Jan 11 '14 at 18:46
  • Exactly, and I indeed get a Class> that I should instantiate. Anyway if the question is not clear (it seemed to me) or it is otherwise ambiguous, there is always button "add comment" to ask clarification etc etc before either downvote or provide poor answers @BrianRoach – Niccolò Jan 11 '14 at 18:51
  • @Niccolò Please don't feel offended nor offend anyone. There is no personal comments here. Comments are merely added for questions and answers. – Rohit Jain Jan 11 '14 at 19:17
  • No offense intended :) I was just surprised by the speed of comments and votes (both to question and answers), without actually anyone asking clarification. – Niccolò Jan 11 '14 at 21:13
-1

If you use it in reflect method, I think you should use

Integer.TYPE
Ivan
  • 653
  • 5
  • 9