frodo
frodo

Reputation: 1571

Instantiate generic class

I have a class which looks like:

public class Entry<Key,Value> {

    private Key k;
    private Value v;

    public Entry(Key k , Value v)
    {
        this.k = k;
        this.v = v;
    }

    public Key getKey()
    {
        return k;
    }

    public Value getValue()
    {
        return v;
    }

}

I am trying to instantiate an instance of this class when my application runs. I only know the class types of Key and Value when my program runs. For example, I only know that Key and Value class types will be String.class and Integer.class. Is there a way to instantiate an Entry with this information ? If not , what could I do to create entries dynamically ?

Thanks!

Upvotes: 0

Views: 38

Answers (1)

zapl
zapl

Reputation: 63955

A program is like

String key = getFromSomewhere();
Integer value = someMethodResult();

means that you do know a type at compile time that is better than Object. So you can do

Entry<String,Integer> entry = new Entry<String,Integer>(key, value);

as well. There is no "not knowing the type at runtime", you will always know that an instance is at least Object and that's something you can use in generic classes as well. You don't need to use the concrete runtime type.

Upvotes: 2

Related Questions