如何将类属性的“相对引用”作为参数传递以提取属性值?
Got it, what you're describing is totally doable in Java using functional interfaces—specifically Function from the java.util.function package. The "relative reference" you're thinking of is essentially a way to tell the method how to get the desired Integer property from each SomeObject in your list.
Here's how to implement it properly:
Step 1: Define the Method with a Function Parameter
Instead of trying to pass a direct property reference (which Java doesn't natively support for fields), you pass a Function that takes a SomeObject and returns the Integer property you want. This function acts as your "property extractor":
import java.util.ArrayList; import java.util.List; import java.util.function.Function; public class YourClass { // Assume this is your list of objects private List<SomeObject> someObjectList; public ArrayList<Integer> getAllPropertyValues(Function<SomeObject, Integer> propertyExtractor) { ArrayList<Integer> temp = new ArrayList<>(); for (SomeObject x : someObjectList) { // Use the function to get the property value from each object temp.add(propertyExtractor.apply(x)); } return temp; } }
Step 2: Call the Method with a Property Extractor
Now you can pass different property extractors depending on which value you want to pull. The easiest way is to use method references if your SomeObject has getter methods for its properties:
// Suppose SomeObject has getAge() and getScore() methods that return Integer YourClass yourInstance = new YourClass(); // Extract all age values ArrayList<Integer> ages = yourInstance.getAllPropertyValues(SomeObject::getAge); // Extract all score values ArrayList<Integer> scores = yourInstance.getAllPropertyValues(SomeObject::getScore);
If you don't have getters (though you really should use encapsulation!), you can use a lambda expression to access the field directly:
// Access a public field directly (not recommended, but works) ArrayList<Integer> values = yourInstance.getAllPropertyValues(x -> x.someIntegerField);
Why This Works
The Function interface lets you encapsulate the logic of retrieving the property. Instead of hardcoding which property to fetch in the method, you let the caller decide by passing in that logic. This makes your method reusable for any Integer property of SomeObject.
内容的提问来源于stack exchange,提问作者Alex Coronas

