[英]Is there a way to assign a String object as a custom class instance?
Tried to extend from String class but it is final, hence looking for a way so that I can assign a String object as my custom class instance? 试图从String类扩展,但是它是最终的,因此正在寻找一种方法,以便可以将String对象分配为自定义类实例?
Example: 例:
public class MyClass {
public CustomString cString;
}
MyClass myClass = new MyClass();
Field field = myClass.getField("cString");
field.set(myClass, "TestValue");
If you must do this with reflection, how about using methods instead of fields. 如果必须通过反射来执行此操作,那么如何使用方法而不是字段。 Specifically, try using a setter convention like so:
具体来说,请尝试使用如下的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());
}
This way you can still use the field names but allow the field to be set by a method which can be arbitrarily interesting. 这样,您仍然可以使用字段名称,但是允许通过一种可能会引起兴趣的方法来设置字段。
You can set the field with a little encapsulation. 您可以对字段进行一些封装。 If the field's type is
CustomString
, we transform the value to CustomString
object. 如果字段的类型为
CustomString
,则将值转换为CustomString
对象。 Here is the complete codde: 这是完整的代码:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.