Instantiating a generic class in Java

2018-12-31 08:03发布

I know Java's generics are somewhat inferior to .Net's.

I have a generic class Foo<T>, and I really need to instantiate a T in Foo using a parameter-less constructor. How can one work around Java's limitation?

标签: java generics
9条回答
牵手、夕阳
2楼-- · 2018-12-31 08:10

And this is the Factory implementation, as Jon Skeet suggested:

interface Factory<T> {
    T factory();
}

class Araba {
    //static inner class for Factory<T> implementation
    public static class ArabaFactory implements Factory<Araba> {
        public Araba factory() {
            return new Araba();
        }
    }
    public String toString() { return "Abubeee"; }
}

class Generic<T> {
    private T var;

    Generic(Factory<T> fact) {
        System.out.println("Constructor with Factory<T> parameter");
        var = fact.factory();
    }
    Generic(T var) {
        System.out.println("Constructor with T parameter");
        this.var = var;
    }
    T get() { return var; }
}

public class Main {
    public static void main(String[] string) {
        Generic<Araba> gen = new Generic<Araba>(new Araba.ArabaFactory());
        System.out.print(gen.get());
    }
}

Output:

Constructor with Factory<T> parameter
Abubeee
查看更多
梦醉为红颜
3楼-- · 2018-12-31 08:14

From https://stackoverflow.com/a/2434094/848072. You need a default constructor for T class.


import java.lang.reflect.ParameterizedType;

class Foo {

  public bar() {
    ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
    Class type = (Class) superClass.getActualTypeArguments()[0];
    try {
      T t = type.newInstance();
      //Do whatever with t
    } catch (Exception e) {
      // Oops, no default constructor
      throw new RuntimeException(e);
    } 
  }
}

查看更多
初与友歌
4楼-- · 2018-12-31 08:15

Quick solution that worked for me. I see there is already an answer for this and this may not even be the best way to go about it. Also, for my solution you'll need Gson.

However, I ran into a situation where I needed to create an instance of a generic class of type java.lang.reflect.Type.

The following code will create an instance of the class you want with null instance variables.

T object = new Gson().fromJson("{}", myKnownType);

Where myKnownType is known before hand and obtained via TypeToken.getType().

You can now set appropriate properties on this object. Again, this may not be the best way to do this but it works as a quick solution if that's what you need.

查看更多
只若初见
5楼-- · 2018-12-31 08:21

For Java 8 ....

There is a good solution at https://stackoverflow.com/a/36315051/2648077 post.

This uses Java 8 Supplier functional interface

查看更多
弹指情弦暗扣
6楼-- · 2018-12-31 08:28

I really need to instantiate a T in Foo using a parameter-less constructor

Simple answer is "you cant do that" java uses type erasure to implment generics which would prevent you from doing this.

How can one work around Java's limitation?

One way (there could be others) is to pass the object that you would pass the instance of T to the constructor of Foo<T>. Or you could have a method setBar(T theInstanceofT); to get your T instead of instantiating in the class it self.

查看更多
伤终究还是伤i
7楼-- · 2018-12-31 08:30

Here's a rather contrived way to do it without explicitly using an constructor argument. You need to extend a parameterized abstract class.

public class Test {   
    public static void main(String [] args) throws Exception {
        Generic g = new Generic();
        g.initParameter();
    }
}

import java.lang.reflect.ParameterizedType;
public abstract class GenericAbstract<T extends Foo> {
    protected T parameter;

    @SuppressWarnings("unchecked")
    void initParameter() throws Exception, ClassNotFoundException, 
        InstantiationException {
        // Get the class name of this instance's type.
        ParameterizedType pt
            = (ParameterizedType) getClass().getGenericSuperclass();
        // You may need this split or not, use logging to check
        String parameterClassName
            = pt.getActualTypeArguments()[0].toString().split("\\s")[1];
        // Instantiate the Parameter and initialize it.
        parameter = (T) Class.forName(parameterClassName).newInstance();
    }
}

public class Generic extends GenericAbstract<Foo> {
}

public class Foo {
    public Foo() {
        System.out.println("Foo constructor...");
    }
}
查看更多
登录 后发表回答