尝试从String类扩展,但它是final,因此寻找一种方法,以便我可以将String对象指定为我的自定义类实例?
示例:
public class MyClass {
public CustomString cString;
}
MyClass myClass = new MyClass();
Field field = myClass.getField("cString");
field.set(myClass, "TestValue");
答案 0 :(得分:2)
如果必须使用反射来完成此操作,那么如何使用方法而不是字段。具体来说,尝试使用像这样的setter约定:
class MyClass {
private CustomString customString = new CustomString();
public CustomString getCustomString() {
return customString;
}
public String getCustomStringValue() {
return customString.getValue();
}
public void setCustomString(String customString) {
this.customString.setValue(customString);
}
}
class CustomString {
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
}
public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
String fieldName = "customstring";
MyClass myClass = new MyClass();
Method[] methods = myClass.getClass().getMethods();
for(Method method : methods) {
String name = method.getName();
if (name.equalsIgnoreCase("set" + fieldName) {
method.invoke(myClass, "Hello");
}
}
System.out.println(myClass.getCustomStringValue());
}
这样你仍然可以使用字段名称,但允许通过一个可以随意使用的方法来设置字段。
答案 1 :(得分:0)
您可以使用一点封装来设置字段。如果字段的类型为CustomString
,我们会将值转换为CustomString
对象。这是完整的密码:
import java.lang.reflect.Field;
public class Q47027440 {
public static void main(String[] args) throws Exception {
MyClass myClass = new MyClass();
Field field = MyClass.class.getField("str");
set(field, myClass, "TestValue");
System.out.println(myClass.str.actual);
}
public static void set(Field field, Object obj, Object value)
throws InstantiationException, IllegalAccessException {
if (field.getType() == CustomString.class && value instanceof String) {
CustomString cs = CustomString.class.newInstance();
cs.actual = (String) value;
value = cs;
}
field.set(obj, value);
}
public static class CustomString {
public String actual;
}
public static class MyClass {
public CustomString str;
}
}