Maybe I am having some problems understanding generics, but I can’t do something that looks logical to me. Maybe you can clarify it for me.
I am developing a Java Library and there is a function that will call a platform that will return information in the JSON format. I wanted to create a namespace responsible for retrieving and parsing the JSON information into business objects. To do that, I created this:
JSON class – Has 2 methods:
protected JSONObject readJsonFromUrl(String url)
open the stream and download the JSON file
public <T, U extends Parser> T readObjectFromUrl(String url, U parser)
is the “entry point”. Will call the readJsonFromUrl, and call the returned value to the parser.
The Parser class is an abstract class and has this interface
public abstract class Parser {
public abstract <T> T parse(JSONObject jsonObject);
}
What I wanted to do is to create a subclass that overrides the parse method, each subclass would return a different type.
For instance, a contact list parser would look like this:
public <T> T parse(JSONObject jsonObject) {
ContactList contactList = new ContactList();
//Simplified for clearness
contactList = parse(jsonObject);
return contactList;
}
The problem is: I get a compiler error because it is expecting a T, and not a contactList.
If I change to , the signature of the new method do not match the signature of the parent class.
If I change the contactList’s declaration to T contactList;, I can’t call some methods I need (for instance addContact).
Am I getting generics wrong? Are they suited for what I want in this case?
If they are not, how would you implement a similar functionality?
Thanks,
Oscar
Edit: is the best solution to use Object instead of generics? It doesn’t seem so pretty 🙁
You’re using generics on a method which returns always the same type of Objects, and that type may vary depending on the implementation of the method.
Then I guess you should move your generic declaration to the class.
And your implementation will look like :