-1

Possible Duplicate:
Create instance of generic type in Java?

I got these classes

public abstract class Base {
    public String Id = "originalId";
}

public class InstanceOfBase extends Base {
    public void setString(String test) {
        this.Id = test;
    }
}

public class UseIt {
    public Test<InstanceOfBase> test = new Test<InstanceOfBase>();

    public void run() {
        InstanceOfBase instanceOfBase = test.createMe();
        System.out.println(instanceOfBase.Id);
    }
}

public abstract class Test<E extends Base> {
    public E createMe() {
        // How do I do this?
        return new E();
    }
}

The code above does not compile because it does not know how to create E. how can I achieve this?

When I invoke the run method, I expect it should print "originalId".

Community
  • 1
  • 1
user1051218
  • 395
  • 2
  • 16
  • Note that one of the reasons why it is not possible without reflection is that if `InstanceOfBase` had a private constructor, for example, it would not be instantiable with `new`. – assylias Dec 31 '12 at 11:47

1 Answers1

2

Unfortunately you cannot create classes from generic types in java. But you can do as Justin Rudd suggested in this thread and write:

public E createMe(Class<E> clazz)
{
    return clazz.newInstance();
}

So you use the class archetype to create a new instance. Invoking it could be:

InstanceOfBase instanceOfBase = test.createMe(test.getClass)
Community
  • 1
  • 1
Jens Egholm
  • 2,730
  • 3
  • 22
  • 35