I want to create some utility method and I want it to be able to work on different objects as long as they can provide an Integer property that is read/write.
I know the "Standard" way would be to:
- declare some interface
IProvidesAccessToIntegerthat hassetIntegerandgetInteger. - declare
MyUtility.doSomethingWonderful(IProvidesAccessToInteger obj) - make calls to
obj.setIntegerandobj.getInteger.
But this has a very strong downside that it requires the cooperation of all those classes that I want MyUtility to work with and not only that but even if some class wants to cooperate MyUtility would still only be able to .doSomethingWonderful() to just a single predetermined field of that classes.
I am looking for some syntax that would allow for something like MyUtility.doSomethingWonderful(T obj, Method<Integer> getter, Method<Integer,Integer> setter) maybe using generics somehow to specify the requirement that objhas two methods that get set and set an Integer and have some way to call them on the instance of obj.
It might also be interesting to do something similar with static methods that do not need an object.
UPDATE: As I was pointed to reflection, I want to clarify that I know close things can be done using reflection.
However since I don't need to resolve the actual interface in runtime I had the hope that JAVA has some way to specify sort of an "Interface fulfilment map" such that If my requirement would be an object that has two methods int ?() and void ?(int) I could specify something like .doSomethingWonderful(?<int getter(),void setter(int)> obj) and call it once with some object1 that has int getInt() and void setInt(int) and once with some other object2 that has int getIntValue() and void setIntValue(int) by specifying in the calls that object fulfills the requirements for getInteger by getInt and fulfills the requirements for setInteger by setInt and so on. maybe with a call syntax like `.doSomethingWonderful((?)object1)
At least in theory I think it should be possible to do all at compile time and not require any runtime reflection.
maybe the right name for this would by an anonymous interface.
that said, I accept that a runtime solution via reflection might also be a solution.