Reputation: 13437
I'm trying to pass a subclass as a parameter and then create an instance of it, but I'm getting the error message on the line where I instantiate the transformation class (incompatible types). If I try to instantiate using transClass trans = new transClass()
, it complains that transClass
is unknown. Here's the code I'm using.
abstract class Transformation {
abstract public Object transform(Object obj);
}
class MyTransformation extends Transformation {
public Object transform(Object obj){
// do stuff to obj
return obj;
}
}
class AnotherClass {
public doSomething(Object obj, Class<Transformation> transClass){
// do more stuff to obj
Transformation trans = new transClass(); // fails with "Incompatible Types", referring to 'Transformation' and 'transClass'
// transClass trans = new transClass(); // alternate attempt, also fails with "Unknown Type" on 'transClass'
return trans.transform(obj);
}
}
Upvotes: 0
Views: 57
Reputation: 85779
You should use Class#newInstance
:
public <T extends Transformation> Object doSomething(Object obj, Class<T> transClass)
throws Exception {
// do more stuff to obj
Transformation trans = transClass.newInstance();
return trans.transform(obj);
}
Upvotes: 5