简体   繁体   English

Java泛型类型和方法

[英]Java generic types and methods

I want to create a function that gets an List parameter and creates a certain jsonResult. 我想创建一个获取List参数并创建某个jsonResult的函数。 I know in advance that every T object of mine will have a getId() function. 我事先知道我的每个T对象都有一个getId()函数。 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. 调用item.getId()的行当然会给我一个错误。 How can I bypass it. 我怎么能绕过它呢。 I am using type to also to pass the class type to use it for casting. 我也使用type来传递类类型以用于转换。 But I still get an error. 但我仍然得到一个错误。 Is there a way to use T but and call methods from specific object? 有没有办法使用T但是从特定对象调用方法?

For example every of your T will implement an interface of abstract class which has this function has getID(). 例如,你的每个T都将实现一个抽象类的接口,该接口具有此函数的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: 然后确保传递给此方法的每个类型实际使用此接口(或您可能已经拥有的任何其他接口/类),您可以使用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. 从现在开始,getID()函数可用。

You get an error because the java compiler does not know the T has a method like get Id. 你得到一个错误,因为java编译器不知道T有一个像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. 不要忘记让您的类实现SomeInterface。

Also, you can just use 此外,你可以使用

<T extends SomeInterface>

to fix that problem. 解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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