Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating instance from a generic class when a constructor init parameteres [duplicate]

Tags:

java

generics

Possible Duplicate:
How to create instance of a class with the parameters in the constructor using reflection?

Is it possible to happen and how? I have a class Gerbil :

public class Gerbil {
    private int gerbilNumber;
    public Gerbil(int gn){
        this.gerbilNumber = gn;
    }
    public void hop() {
        System.out.println("It's gerbil number" + this.gerbilNumber + "and it's hopping.");
    }

}

I have a generic class TestGenerics:

public class TestGenerics<T> {
    private Class<T> mClass;

    public TestGenerics(Class<T> cls){
        mClass = cls;
    }

    public T get(){
        try{
            return mClass.newInstance();
        }catch(Exception e){
            e.printStackTrace();
            return null;
        }
    }
}

And a main class:

public class HelloWorld {
    public static void main(String[] args) {
        TestGenerics<Gerbil> g = new TestGenerics<Gerbil>(Gerbil.class);
        Gerbil a = g.get();
        a.hop();
    }
}

The problem is that I need to provide the constructor of Gerbil with an integer value but don't know how (if possible). Otherwise if I leave an empty/default constructor the code is working fine, but is it possible to make an instance form a generic class when the constructor of the real class need parameters to be passed?

like image 336
Leron_says_get_back_Monica Avatar asked Dec 20 '22 14:12

Leron_says_get_back_Monica


1 Answers

Try this:

public T get(){
    try{
        return mClass.getDeclaredConstructor( Integer.TYPE ).newInstance( 10 );
    }catch(Exception e){
        e.printStackTrace();
        return null;
    }
}
like image 66
stemm Avatar answered Jan 03 '23 04:01

stemm