Reputation: 8101
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?
Upvotes: 2
Views: 129
Reputation: 3164
For example every of your T will implement an interface of abstract class which has this function has getID().
E.g.:
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.
Upvotes: 11
Reputation: 11
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.
Upvotes: 1