-3

I want to create objects from different classes extending the same class. Can you explain how it will work. Examples would be nice.

Thank you.

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);...}
erickson
  • 265,237
  • 58
  • 395
  • 493
Janneck Lange
  • 882
  • 2
  • 11
  • 34

2 Answers2

1

Instead of

new clazz();

try

clazz.newInstance();

Good luck

Lebanner
  • 38
  • 1
  • 8
1

It looks like you want to create an instance of a dynamically selected class. Obtain a constructor with getConstructor(), and invoke it with the necessary arguments. The Class object has a newInstance() method which is almost the same, but using a Constructor will report any errors in a manner more consistent with other reflective methods.

Constructor<T> ctor = clazz.getConstructor(Integer.TYPE, Integer.TYPE);
T point = ctor.newInstance(2, 3);
erickson
  • 265,237
  • 58
  • 395
  • 493
  • Constructor must be public of course... Thank you very much! – Janneck Lange Dec 03 '19 at 01:23
  • @JanneckLange You can grant yourself access to the constructor if necessary: [`setAccessible()`](https://docs.oracle.com/javase/8/docs/api/java/lang/reflect/AccessibleObject.html#setAccessible-boolean-) Of course, if there's a security manager installed and you don't have the necessary permissions, this attempt to escalate access will fail. – erickson Dec 03 '19 at 01:24