views:

132

answers:

3

My question is very similar to this question. I want to be able to instantiate an object of the type parameter type, but also without needing to pass in a "factory". I really need to be contained all in the one class.

public class myClass<E> {
    E someObject;

    public myClass(){
      someObject = new E();
    }
}

Previous solutions required the constructor of myClass to be changed to have a factory parameter, and then to call the constructor of that, but for my purposes I don't want to modify any calls to myClass from the outside.

Any help? If I didn't explain well, I can add more. Thanks.

+1  A: 

No, as explained in answers to the linked question, you can't do that. Modify the interface to pass in a factory object. (NB: Class makes a bad factory.)

Tom Hawtin - tackline
+5  A: 

The problem is that you don't know what E is, nor how to construct it. It could be any type (it's universally quantified). You need to supply evidence that, whatever E is, it can really be constructed. A "factory" of a given type serves as a kind of witness to the fact that it can.

Think about this for a second: What if I pass Void as the parameter E? How would you go about constructing a value of type Void?

Being able to construct E for all E would be like creating something out of nothing. It's a logical impossibility. ∀E. E is an uninhabited set.

What you really want is either for E to have a bound, or to pass a constructor (factory) as a witness of the fact that E is in the set of constructable objects.

Apocalisp
A: 

You know your code doesn't work, and you are expecting a solution with a close enough syntax.

How about this?

//doesn't work. cannot make x.someObject a new String()
//MyClass<String> x = new MyClass<String>();

//this can work...
MyClass<String> x = MyClass.neu(String.class);

public class MyClass<E>
{
    static public <T> MyClass<T> neu(Class<T> clazz){...}
}
irreputable