Instantiating generics type in java

2019-01-01 13:39发布

Duplicate: Java generics why this won’t work

Duplicate: Instantiating a generic class in Java

I would like to create an object of Generics Type in java. Please suggest how can I achieve the same.

Note: This may seem a trivial Generics Problem. But I bet.. it isn't. :)

suppose I have the class declaration as:

public class Abc<T> {
    public T getInstanceOfT() {
       // I want to create an instance of T and return the same.
    }
}

标签: java generics
12条回答
深知你不懂我心
2楼-- · 2019-01-01 13:51

I was implementing the same using the following approach.

public class Abc<T>
{
   T myvar;

    public T getInstance(Class<T> clazz) throws InstantiationException, IllegalAccessException
    {
        return clazz.newInstance();
    }
}

I was trying to find a better way to achieve the same.

Isn't it possible?

查看更多
临风纵饮
3楼-- · 2019-01-01 13:52

You don't seem to understand how Generics work. You may want to look at http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html Basically what you could do is something like

public class Abc<T>
{
  T someGenericThing;
  public Abc(){}
  public T getSomeGenericThing()
  {
     return someGenericThing;
  }

  public static void main(String[] args)
  {
     // create an instance of "Abc of String"
        Abc<String> stringAbc = new Abc<String>();
        String test = stringAbc.getSomeGenericThing();
  }

} 
查看更多
大哥的爱人
4楼-- · 2019-01-01 13:53
public class Abc<T> {
    public T getInstanceOfT(Class<T> aClass) {
       return aClass.newInstance();
    }
}

You'll have to add exception handling.

You have to pass the actual type at runtime, since it is not part of the byte code after compilation, so there is no way to know it without explicitly providing it.

查看更多
浪荡孟婆
5楼-- · 2019-01-01 13:54

Type Erasure Workaround

Inspired by @martin's answer, I wrote a helper class that allows me to workaround the type erasure problem. Using this class (and a little ugly trick) I'm able to create a new instance out of a template type:

public abstract class C_TestClass<T > {
    T createTemplateInstance() {
        return C_GenericsHelper.createTemplateInstance( this, 0 );
    }

    public static void main( String[] args ) {
        ArrayList<String > list = 
            new C_TestClass<ArrayList<String > >(){}.createTemplateInstance();
    }
}

The ugly trick here is to make the class abstract so the user of the class is forced to subtype it. Here I'm subclassing it by appending {} after the call to the constructor. This defines a new anonymous class and creates an instance of it.

Once the generic class is subtyped with concrete template types, I'm able to retrieve the template types.


public class C_GenericsHelper {
    /**
     * @param object instance of a class that is a subclass of a generic class
     * @param index index of the generic type that should be instantiated
     * @return new instance of T (created by calling the default constructor)
     * @throws RuntimeException if T has no accessible default constructor
     */
    @SuppressWarnings( "unchecked" )
    public static <T> T createTemplateInstance( Object object, int index ) {
        ParameterizedType superClass = 
            (ParameterizedType )object.getClass().getGenericSuperclass();
        Type type = superClass.getActualTypeArguments()[ index ];
        Class<T > instanceType;
        if( type instanceof ParameterizedType ) {
            instanceType = (Class<T > )( (ParameterizedType )type ).getRawType();
        }
        else {
            instanceType = (Class<T > )type;
        }
        try {
            return instanceType.newInstance();
        }
        catch( Exception e ) {
            throw new RuntimeException( e );
        }
    }
}
查看更多
忆尘夕之涩
6楼-- · 2019-01-01 14:03

What you wrote doesn't make any sense, generics in Java are meant to add the functionality of parametric polymorphism to objects.

What does it mean? It means that you want to keep some type variables of your classes undecided, to be able to use your classes with many different types.

But your type variable T is an attribute that is resolved at run-time, the Java compiler will compile your class proving type safety without trying to know what kind of object is T so it's impossible for it to let your use a type variable in a static method. The type is associated to a run-time instance of the object while public void static main(..) is associated to the class definition and at that scope T doesn't mean anything.

If you want to use a type variable inside a static method you have to declare the method as generic (this because, as explained type variables of a template class are related to its run-time instance), not the class:

class SandBox
{
  public static <T> void myMethod()
  {
     T foobar;
  }
}

this works, but of course not with main method since there's no way to call it in a generic way.

EDIT: The problem is that because of type erasure just one generic class is compiled and passed to JVM. Type checker just checks if code is safe, then since it proved it every kind of generic information is discarded.

To instantiate T you need to know the type of T, but it can be many types at the same time, so one solution with requires just the minimum amount of reflection is to use Class<T> to instantiate new objects:

public class SandBox<T>
{
    Class<T> reference;

    SandBox(Class<T> classRef)
    {
        reference = classRef;
    }

    public T getNewInstance()
    {
        try
        {
            return reference.newInstance();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args)
    {
        SandBox<String> t = new SandBox<String>(String.class);

        System.out.println(t.getNewInstance().getClass().getName());
    }
}

Of course this implies that the type you want to instantiate:

  • is not a primitive type
  • it has a default constructor

To operate with different kind of constructors you have to dig deeper into reflection.

查看更多
流年柔荑漫光年
7楼-- · 2019-01-01 14:03

The only way to get it to work is to use Reified Generics. And this is not supported in Java (yet? it was planned for Java 7, but has been postponed). In C# for example it is supported assuming that T has a default constructor. You can even get the runtime type by typeof(T) and get the constructors by Type.GetConstructor(). I don't do C# so the syntax may be invalid, but it roughly look like this:

public class Foo<T> where T:new() {
    public void foo() {
        T t = new T();
    }
}

The best "workaround" for this in Java is to pass a Class<T> as method argument instead as several answers already pointed out.

查看更多
登录 后发表回答