简体   繁体   中英

Java generic types and methods

I want to create a function that gets an List parameter and creates a certain jsonResult. I know in advance that every T object of mine will have a getId() function. So my method

private static <T> JsonObject createJsonAarrayResult(List<T> items, Class<T> type){
    JsonObject jsonResult = new JsonObject();
    JsonArray jsonResultItem = new JsonArray();
    for (T item : items){
        JsonObject jsonArrayItem = new JsonObject();
        jsonResultItem.addProperty("id", item.getId());

    }
    return jsonResult;
}

The line that calls item.getId() of course gives me an error. How can I bypass it. I am using type to also to pass the class type to use it for casting. But I still get an error. Is there a way to use T but and call methods from specific object?

For example every of your T will implement an interface of abstract class which has this function has getID().

Eg:

public interface InterfaceID {
    String getID();
}

Then make sure that each of your types you pass to this method actually use this interface (or any other Interface/Class which you may already have) you can declare the generic with extends:

 private static <T extends InterfaceID> JsonObject createJsonAarrayResult(List<T> items){
    ....
    // The Class<T> parameter is not needed in your example and can be removed.

From now on the getID() function is available.

You get an error because the java compiler does not know the T has a method like get Id. You can write an interface like:

public interface SomeInterface {  
    long getId();
}

Then modify your interface like this.

private static <T> JsonObject createJsonAarrayResult(List<SomeInterface> items, Class<T> type){
   ...
}

Don't forget to let your class implements SomeInterface.

Also, you can just use

<T extends SomeInterface>

to fix that problem.

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