generics - Java Prevent code duplication when getting a list of a property in each Object from a list of Objects -
I have several objects that look like this:
class PhoneNumber {String getNumber (); String Mill Extension (); Receive date time for the host (); } Class address {string getCity (); String hoststate (); Int getZip (); }
I want to be able to take a list of one of those items and get a list of a special property. This is a trivial operation if I want to write a function for every property, but as I think, duplicating this code several times is bad behavior.
So I want to be able to do something for any object either in the object:
list & lt; Address & gt; Address = address = get (); & Lt; String & gt; CityList = getListOfProperties (address list, Address.getCity / * <-> to populate a list returned with instructions in the form of property * /)
I try to do this I have racked my mind in with generic, I'm not even sure that this is possible, but as I think, many magical things can be done with Java programming language.
You can do this work with generic and a utility class. I feel slightly better at using this reflection because you are checking the time that the property you are retrieving is present (and not misspelled etc).
First of a class that performs a real conversion, note the abstract "go" method, which we will override in an anonymous Inner class when we call getListOfProperties ().
Public abstract category list property garter & lt; R, T & gt; {/ ** Looking at a source object, R. * Return of some property of Public Essence R (T Source); / ** By looking at a list of objects, use the "received" method to retrieve a single property from each list item and return a listing of those property values. * / Public Final List & lt; R & gt; GetListOfProperties (List & lt; T & gt; List) {List & lt; R & gt; Rate = New Arrestist & lt; R & gt; (List.size ()); For (T source: list) {ret.add (get (source)); } Return return; }}
Then you use it like this. Not a beautiful liner, but compile good to check time:
list & lt; PhoneNumber & gt; PhoneNumbers = New Arrestists & lt; PhoneNumber & gt; (); // Add some phone numbers to the list & lt; String & gt; Extension = New ListProjector & lt; String, Phononumber & gt; () {@ Override public string received (PhoneName source) {return source.getExtension (); }} .getListOfProperties (phoneNumbers);
Comments
Post a Comment