I would like to create an instance of a generic type used as a function parameter. Suppose the following classes with a different representation of a point
class Point1 {
double x, y;
public Point1 (double x_, double y_) {x=x_; y = y_;}
}
class Point2 {
double lat, lon;
public Point2 (double lat_, double lon_) {lat = lat_; lon = lon_;}
}
There is a class creating an instance of the generic type based on the reflection
public class GType<T> {
private Class<T> UType;
public GType(Class<T> gt) {UType = gt;}
public T get(double p1, double p2){
try {
Class[] constrArg = new Class[2];
constrArg[0] = double.class;
constrArg[1] = double.class;
return UType.getDeclaredConstructor(constrArg).newInstance(p1, p2);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
While
public static void main(String[] args) {
GType<Point1> gt = new GType<>(Point1.class);
Point1 p = gt.get(10,10);
}
works well, the following construction
public static <Point> void test (Point point){
GType<Point> g = new GType<>(Point.class); //Error
point = g.get(10,10,10);
}
public static void main(String[] args) {
Point1 p1;
test (p1);
}
leads to
Error: Cannot select from a type variable
How to to create an instance of the Point1 type inside the test() function, where Point = Point1? Thanks for your help.
Updated question:
Is there a solution with the Lambda function for a method with the unknown Point instance:
public static <Point> void test (List<Point> points)
{
GType<Point> g = new GType<>((Class)points.getClass());
Point point = g.get(10,10);
points.add(point);
}
<Point>in the method declaration does?Supplier<T>that would return a new instance ofT) over reflection.javac.