Search code examples
javalistclassparameters

"Relative" class property referencing


I want to pass a "relative" reference of a class property as a parameter.

First of all, I don't know if "relative reference" is actually the proper name for this, but what I have in mind is something along these lines:

public ArrayList<Integer> getAllPropertyValues(someObjectClass.someInteger) { //someObjectClass.someInteger being the "relative reference"
    ArrayList<Integer> temp = new ArrayList<>();
    for (someObject x : someObjectList) {
        temp.add(x.someInteger);
    }
}

The idea would be to pass a reference to (for example) Human.Age and the method would add to the list each x.Age.

In other words, given an object x if I pass the property y i'd be able to call someDataType recievedProperty = x.y. Regarldess of which kind object is x or what type is y.

Is there a way to do this in Java?


Solution

  • I think that you could use a ToIntFunction that accepts a SomeObjectClass and returns an int.

     public ArrayList<Integer> getAllPropertyValues(ToIntFunction<SomeObjectClass> function) { 
        ArrayList<Integer> temp = new ArrayList<>();
        for (someObject x : someObjectList) {
            temp.add(function.apply(x));
        }
     }
    

    And you could invoke it :

    ArrayList<Integer> results = getAllPropertyValues(SomeObjectClass::getAge);
    

    You could pass getAge() or any method of SomeObjectClass that returns an int.