从类实例创建对象

詹内克·朗格

我想从扩展同一类的不同类创建对象。你能解释一下它是如何工作的。例子会很好。

谢谢你。

class MainClass{

   private <T extends DataPoint> void someMethod(Class<T> clazz) {
      new clazz(2,3);//<-- create object of class (did not work)
   }

   private void anotherClass(){
      someMethod(GreenDataPoint.class);
      someMethod(BlueDataPoint.class);
   }
}

class DataPoint {
   int x;
   int y;
   DataPoint(int x, int y) {
      this.x = x;
      this.y = y;
   }
}

class BlueDataPoint extends DataPoint {BlueDataPoint(int x, int y){super(x,y);...}}

class GreenDataPoint extends DataPoint {GreenDataPoint (int x, int y){super(x,y);...}
埃里克森

看起来您想创建一个动态选择的类的实例。使用 获取构造函数getConstructor()使用必要的参数调用它Class对象有一个newInstance()几乎相同方法,但使用 aConstructor将以与其他反射方法更一致的方式报告任何错误。

Constructor<T> ctor = clazz.getConstructor(Integer.TYPE, Integer.TYPE);
T point = ctor.newInstance(2, 3);

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章