简体   繁体   中英

Extract Java Type from generic object

I am creating a class with a lot of methods that are similar to the getCategories() method in the snippet. Is there a way to make a method that gets the Type object that i need for the next operation dynamically instead of typing and repeating myself for other similar methods.

import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.List;

...

    public static void getCategories(CategoriesCallback<List<Category>> callback) {
        //Need to create a method to get Type from the callback object instead of manually typing it
        Type type = new TypeToken<List<Category>>() {}.getType();
        //Requires Callback and Type
        performOperation(callback, type);
    }

    //e.g.
    public static void getBooks(BooksCallback<List<Book>> callback) {
        //Need to create a method to get Type from the callback object instead of manually typing it
        Type type = new TypeToken<List<Book>>() {}.getType();
        //Requires Callback and Type
        performOperation(callback, type);
    }

...

Yes, it's possible to develop a base generic class that are extended by CategoriesCallback and BooksCallback. You will have something like this

public class BaseCallback<T> {
}

And these are those classes:

public class BooksCallback<Book> extends BaseCallback<List<Book>>{
}
public class CategoriesCallback<Category> extends BaseCallback<List<Category>>{
}

And now you can have your own base general method as this:

public static void getCallbacks(BaseCallback<List<?>> callback) {
        
}

Need to create a method to get Type from the callback object instead of manually typing it

This is a FAQ. The only way to do this is a hack and is considered back form due to Java using type erasure . The collection does not know what type is holding since that information is only available at compilation time.

If you really and truly need the type then I would pass it into your method:

public static <T> void getCategories(CategoriesCallback<List<T>> callbackList,
      Class<T> clazz) {

Then you would call it like:

List<Foo> callbackList = ...
getCategories(callbackList, Foo.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM