JMohasin
JMohasin

Reputation: 533

How to call constructor of class in generic method?

I am trying to create generic function to minimize repeated code. I have following function (without Generic applied)

public ModelClass getModelDataList (String arg1)
{
        ModelClass objModelClass = new ModelClass(new JSONObject(arg1));
        return objModelClass;
}

so now i am trying to make it generic so that i can Use any ModelClass with it (e.g. Student,Department, College etc) so i found code by searching on Google

public static <T> T f(String response) 
    {
        T typeList = new T(new JSONObject(response));
        return typeList ;
    }

Can somebody tell me how to achieve this.

Thanks in advance.

Upvotes: 1

Views: 368

Answers (2)

JMohasin
JMohasin

Reputation: 533

I figured out another way to do this by making use of interfaces & abstract method inheritance

Upvotes: 0

Tom Hawtin - tackline
Tom Hawtin - tackline

Reputation: 147164

No, you can't constrain a generic parameter to have a particular constructor. Nor should you want to.

The standard course of action is to pass in the abstract factory. Java SE 8 may well introduce a concise form for single method interfaces.

Upvotes: 4

Related Questions