为泛型类的泛型方法的属性赋值 - Java
I need a generic method for assign a value to an attribute of a generic class; I'll do an example to better explain. The method I need I suppose should be something like that:
我需要一个泛型方法来为泛型类的属性赋值;我会做一个例子来更好地解释。我想我需要的方法应该是这样的:
import java.util.function.Function;
public class Utilities {
public static <T> Object assignValueToAttribute( Object MY_Object__Arg, Function<T, ?> MY_AttributeValueExtractor_Arg, Object MY_AttributeValueToEqual_Arg) {
return ....
}
}
EXAMPLE:
let's say I have a Class called 'Car' with a NOT STATIC method 'setColor()'. My generic method should return an istance of Car, let's say 'myCar', and assign the value "red" at the attribute 'color'
假设我有一个名为'Car'的类,其中包含NOT STATIC方法'setColor()'。我的通用方法应返回Car的istance,让我们说'myCar',并在属性'color'处指定值“red”
myCar.setColor("red");
My generic method could be invoked with something like that:
我的泛型方法可以用这样的方式调用:
Car myCar= (Car) Utilities.assignValueToAttribute(myCar, oggetto -> oggetto.setColor(), "red");
PROBLEM: I don't know hot to code that method...
问题:我不知道编写该方法的热点......
1 个解决方案
#1
2
You were close. You need two generic types: a type for your object (bean), and a type for the value. You want a BiConsumer, not a Function, because a set-method does not return anything.
你很亲密您需要两种泛型类型:对象的类型(bean)和值的类型。你想要一个BiConsumer,而不是一个函数,因为set方法不返回任何东西。
public static <T, V> T assignValueToAttribute(T obj, BiConsumer<T, V> attributeSetter, V value) {
attributeSetter.accept(obj, value);
return obj;
}
You can then invoke it as:
然后,您可以将其调用为:
assignValueToAttribute(myCar, Car::setColor, "red");
Note that re-assigning myCar
is pointless. It’s the same object that it was before the method call.
请注意,重新分配myCar毫无意义。它与方法调用之前的对象相同。