You can't really have a generic getter if you don't know what you want to get, for example :
boolean myNewBool= get("myString1");
If get
returns something, but you don't really know if this something is compatible with a boolean, and terrible things could happen.
You could try this:
public <T> get(String element){
return (T) elementToGet;
}
But you would have to specify the return type when you call the get method.
String element = myObject.<String>get("element");
Here are the bad sides :
- You can't work directly with primitives
- You can have a lot of ClassCastException
- If you misspell an attribute name you won't see it until you run it
- You don't expose a nice public API, people would have to know evert possible attribute to use it, and as said above, a misspelled attribute (or an inexistant one) wouldn't be seen until runtime.
- You have to know the return time and type it each time you use your method
- You would have to type a really long (and smelly) code in your
get
method either to use each possible attribute (if you still want have some private and not accessible) or worse, use reflection to find the right attribute.
So definitively not a good idea.
What you can do instead is using the good old getters//setters and if there is a lot of them, generate them with your IDE.
Another way would be to use the project lombok.
Resources :
On the same topic :