Mysterious Challenger
Mysterious Challenger

Reputation: 33

Create new object based on generic type

Is it possible to create a new object based on a generic type. For example I have a couple of custom objects and I'd like to call a generic method that creates a new object based on that generic type.

public static void main(String[] args) {
    Customer cust = myObject("str");
    Vendor vend = myObject("str");
    ...
}

public static <T> T myObject(String str) {
    return new T(str);
}

I read a couple of things about this and I know, that you can't do it like that but I just can't get it to work. For example, I've tried type.isInstance(str) but my editor says, that I shouldn't use that and it doesn't really work. So how should this be done?

Upvotes: 0

Views: 865

Answers (1)

Thomas Fritsch
Thomas Fritsch

Reputation: 10127

I don't know why you want to create different types of objects by a common generic method. For me it smells like a bad design.

Having said that, you can achieve it in the following way:

public static <T> T myObject(Class<T> type, String str)
        throws InstantiationException, IllegalAccessException,IllegalArgumentException,
               InvocationTargetException, NoSuchMethodException, SecurityException
{
    return type.getDeclaredConstructor(String.class).newInstance(str);
}

You see, the method above receives a Class argument, so that it knows of which class the newly created object should be. The method first gets the constructor which can accept one String argument. Then you call the contructor to actually create the object.

You see, you the getDeclaredConstructor and newInstance methods might throw a lot of different exceptions. Therefore you would need to handle these exceptions by some try/catch code. (For brevity I omitted this in my code here, and simply added a throws declaration.) This raises some red flags about the design of this approach.

The method above would be used like this:

public static void main(String[] args) throws Exception
{
    Customer customer = myObject(Customer.class, "str");
    Vendor vendor = myObject(Vendor.class, "str");
}

Upvotes: 3

Related Questions