[英]Reflection generic get field value
我正在尝试通过反射获取字段的值。 问题是我不知道该字段的类型,并且必须在获取值时决定它。
此代码导致此异常:
无法将 java.lang.String 字段 com....fieldName 设置为 java.lang.String
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Class<?> targetType = field.getType();
Object objectValue = targetType.newInstance();
Object value = field.get(objectValue);
我尝试强制转换,但出现编译错误:
field.get((targetType)objectValue)
或者
targetType objectValue = targetType.newInstance();
我怎样才能做到这一点?
就像之前回答的那样,您应该使用:
Object value = field.get(objectInstance);
另一种有时更受欢迎的方法是动态调用 getter。 示例代码:
public static Object runGetter(Field field, BaseValidationObject o)
{
// MZ: Find the correct method
for (Method method : o.getMethods())
{
if ((method.getName().startsWith("get")) && (method.getName().length() == (field.getName().length() + 3)))
{
if (method.getName().toLowerCase().endsWith(field.getName().toLowerCase()))
{
// MZ: Method found, run it
try
{
return method.invoke(o);
}
catch (IllegalAccessException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
catch (InvocationTargetException e)
{
Logger.fatal("Could not determine method: " + method.getName());
}
}
}
}
return null;
}
另请注意,当您的类继承自另一个类时,您需要递归确定 Field。 例如,获取给定类的所有字段;
for (Class<?> c = someClass; c != null; c = c.getSuperclass())
{
Field[] fields = c.getDeclaredFields();
for (Field classField : fields)
{
result.add(classField);
}
}
您应该将对象传递给字段的get方法,所以
Field field = object.getClass().getDeclaredField(fieldName);
field.setAccessible(true);
Object value = field.get(object);
我在我的首选项类的 toString() 实现中使用反射来查看类成员和值(简单快速的调试)。
我正在使用的简化代码:
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
Class<?> thisClass = null;
try {
thisClass = Class.forName(this.getClass().getName());
Field[] aClassFields = thisClass.getDeclaredFields();
sb.append(this.getClass().getSimpleName() + " [ ");
for(Field f : aClassFields){
String fName = f.getName();
sb.append("(" + f.getType() + ") " + fName + " = " + f.get(this) + ", ");
}
sb.append("]");
} catch (Exception e) {
e.printStackTrace();
}
return sb.toString();
}
我希望它会对某人有所帮助,因为我也搜索过。
尽管我不太清楚您要实现什么,但我在您的代码中发现了一个明显的错误: Field.get()
需要包含该字段作为参数的对象,而不是该字段的某些(可能)值。 所以你应该有field.get(object)
。
由于您似乎正在寻找字段值,因此您可以通过以下方式获得:
Object objectValue = field.get(object);
无需实例化字段类型并创建一些空/默认值; 或者也许我错过了一些东西。
Integer typeValue = 0;
try {
Class<Types> types = Types.class;
java.lang.reflect.Field field = types.getDeclaredField("Type");
field.setAccessible(true);
Object value = field.get(types);
typeValue = (Integer) value;
} catch (Exception e) {
e.printStackTrace();
}
`
//Here is the example I used for get the field name also the field value
//Hope This will help to someone
TestModel model = new TestModel ("MyDate", "MyTime", "OUT");
//Get All the fields of the class
Field[] fields = model.getClass().getDeclaredFields();
//If the field is private make the field to accessible true
fields[0].setAccessible(true);
//Get the field name
System.out.println(fields[0].getName());
//Get the field value
System.out.println(fields[0].get(model));
`
我在 Kotlin 中发布了我的解决方案,但它也可以与 java 对象一起使用。 我创建了一个函数扩展,因此任何对象都可以使用这个函数。
fun Any.iterateOverComponents() {
val fields = this.javaClass.declaredFields
fields.forEachIndexed { i, field ->
fields[i].isAccessible = true
// get value of the fields
val value = fields[i].get(this)
// print result
Log.w("Msg", "Value of Field "
+ fields[i].name
+ " is " + value)
}}
看看这个网页: https ://www.geeksforgeeks.org/field-get-method-in-java-with-examples/
能够使用以下方法访问类中的私有字段
Beneficiary ben = new Beneficiary();//class with multiple fields
ben.setName("Ashok");//is set by a setter
//then to get that value following was the code which worked for me
Field[] fields = ben.getClass().getDeclaredFields();
for(Field field: fields) {
field.setAccessible(true);//to access private fields
System.out.println(field.get(ben));//to get value
//assign value for the same field.set(ben, "Y");//to set value
}
您使用错误的参数调用 get 。
它应该是:
Object value = field.get(object);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.