如何调用作为参数传递的类的方法

时间:2014-05-16 21:17:32

标签: java

我试图将子类作为参数传递,然后创建它的实例,但是我在实例化转换类的行上得到了错误消息(不兼容的类型)。如果我尝试使用transClass trans = new transClass()进行实例化,则会抱怨transClass未知。这是我使用的代码。

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

1 个答案:

答案 0 :(得分:5)

您应该使用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);
}