Question

I'm not certain if this is possible in Java. Also, I'm not able to figure out what to query on Google for this. Anyway, I want a method that takes as an argument a Class (interface or class) and the method's return type is an instance of that Class. I don't want to have to recast an Object after the fact.

I'm not certain if this feature exists or what the syntax would be. Let's say I have a class named XYZ and here is my pseudo method.

private XYZ createInstance(XYZ.class, other args) {
  ...
  // create an instance of XYZ with other args named "_xyz_"
  ...
  return _xyz_;
}

Now assume XYZ is some sort of generic syntax. Is this possible at all in Java? Thanks for any help.

Was it helpful?

Solution

private <T> T createInstance(Class<? extends T> c) {
    return c.newInstance();
}

OTHER TIPS

Use the diamond operator:

private <T> T createInstance(Class<T> concreteClass){
  return concreteClass.newInstance();
}

//usage
Integer i = instanceWithThatMethod.createInstance(Integer.class);

To pass "arguments", you have to get the Constructor of the class matching the desired parameter types, and invoke the call on that one, like this:

private <T> T createInstance(Class<T> concreteClass, String stringArg){
    return concreteClass.getConstructor(String.class).newInstance(stringArg);
}

//usage
SomeClass s = createInstance(SomeClass, "testString");

//equals
SomeClass s = new SomeClass("testString");

//where SomeClass HAS to serve:
public SomeClass(String s){
  ...
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top