justik justik - 1 year ago 62
Java Question

Java: Create instance of a generic type passed as a function parameter

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) {
return null;


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

Answer Source

Java Generics are just about static type-checking. You cannot instantiate a type parameter and you cannot get .class of a type parameter.

Since you're passing in a Point instance, you can ask the instance for its class:


so you can pass that to the GType constructor.

However, this is just the answer to your immediate question. Lyubomyr is right in his comment where he states a better Java idiom is passing in a factory lambda function. In your case you'd like a lambda shape like the following:

(double, double) -> Point

Since such a shape isn't provided in the standard library, you should create your own:

public interface PointConstructor<Point> {
   Point create(double x, double y);

Your GType would become

public class GType<T> {
  private PointConstructor<T> cxor; 
  public GType(PointConstructor<T> cxor) { this.cxor = cxor; }

  public T get(double p1, double p2) { 
    return cxor.create(p1, p2);

and you call it as

GType<Point2> gt = new GType<>(Point2::new);

This both works at runtime and satisfies static type safety.