Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get instance of Class<T> [Runtime-Type Token]

Tags:

java

generics

I create a Preferences class and for the Getters I wan't to use Runtime-Type Token.

So here is my getter method:

public <T> T get(String key, Class<T> clazz) {
    // do some crazy stuff (e.g. Double <-> Float)
}

Up to that, everything works fine. But I would like that the class parameter will be optional.

boolean b = preferences.get(key);

So I add an additional method:

public <T> T get(String key) {
    // return get(key, Class<T>);
}

Now the Question: Is there a way to do that? Is there a way to get an/the instance of Class<T>.

It's possible with a small workaround:

public <T> T get(String key, T... args) {
    return get(key, (Class<T>) args.getClass().getComponentType());
}

public <T> T get(String key, Class<T> clazz) {
    System.out.println("key  : " + key);
    System.out.println("clazz: " + clazz);
}

// using
Boolean b = get("mykey");
like image 719
Marcel Jaeschke Avatar asked May 23 '12 12:05

Marcel Jaeschke


People also ask

What is TypeToken in java?

Forces clients to create a subclass of this class which enables retrieval the type information even at runtime.

Can you create instances of generic type parameters?

A generic type is like a template. You cannot create instances of it unless you specify real types for its generic type parameters. To do this at run time, using reflection, requires the MakeGenericType method.

What does class <?> Mean in Java?

What Does Class Mean? A class — in the context of Java — is a template used to create objects and to define object data types and methods. Classes are categories, and objects are items within each category. All class objects should have the basic class properties.

How do you find the class of an object?

getClass() method returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.


1 Answers

You can't. But if you want to class parameter to be optional, simply pass null and check if it's not null when you use it.

If you want to infer it from the left-hand side - it's not possible.

like image 82
Bozho Avatar answered Nov 09 '22 02:11

Bozho