What I want to do is, create a function that returns a String with generic arguments. Then I need to use a method getName() that is for the specific class (better explain with the code).
Here is the code:
protected StringBuilder createJSON(Collection<E> jsonData) {
StringBuilder JSONBuilder = new StringBuilder();
JSONBuilder.append("{\"options\":[");
int count = jsonData.size();
for(Object obj: jsonData) {
count--;
JSONBuilder.append("{\"label\":\"" + obj.getName() + "\",\"value\":\"" + obj.getName() + "\"}");
if(count>0) {
JSONBuilder.append(",");
}
}
JSONBuilder.append("]}");
return JSONBuilder;
}
createJSON takes a generic collection of objects, the problem is when I need to use getName(). the object that I pass to this function are com.opensymphony.user.UserManager and com.atlassian.jira.ComponentManager, both with getName() method.
You want duck typing. Java doesn’t have it. You’re out of luck.
Since presumably those classes don’t implement an interface with the method you need and you can’t change them, your options are:
instanceof