You cannot have a common recipient unless you know what you want to receive, for example:
boolean myNewBool= get("myString1");
If get returns something, but you really don't know if it is Boolean compatible, and terrible things can happen.
You can try the following:
public <T> get(String element){ return (T) elementToGet; }
But you will need to specify the return type when you call the get method.
String element = myObject.<String>get("element");
Here are the bad sides:
- You cannot directly work with primitives
- You may have a lot of ClassCastException
- If you missed the attribute name, you wonβt see it until you run it.
- You are not publishing a good public API, people should know that it can use the evert attribute to use it, and, as mentioned above, the attribute with an error (or unstable) will not be displayed until executed.
- You must know the return time and enter it each time you use your method.
- You will need to enter a very long (and smelly) code in your
get method, either to use every possible attribute (if you still want to have some private and inaccessible ones), or worse, use reflection to find the correct attribute.
So, finally, not a good idea .
Instead, you can use the good old getters // seters and, if there are a lot of them, generate them using the IDE.
Another way would be to use the lombok project.
Resources:
In the same topic:
source share