使用反射获取字段值

编程入门 行业动态 更新时间:2024-10-26 12:27:39
本文介绍了使用反射获取字段值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我无法获取字段值.我想做的是在运行时获取对象.请让我知道我要去哪里了.

I am not able to get the field value.What I am trying to do is get the Object at runtime. Please let me know where I am going wrong.

Test.class

Test.class

import java.lang.reflect.Field; public class Test { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException { final Field field = Class.forName("com.logging.EX").getDeclaredField("value"); field.setAccessible(true); field.get(Class.forName("com.logging.EX")); }

}

EX.class

public class EX { private String value; public EX(){ value="data"; } /** * @return the value */ public String getValue() { return value; } /** * @param value * the value to set */ public void setValue(String value) { this.value = value; }

}

推荐答案

类似这样的事情...

Something like this...

import java.lang.reflect.Field; public class Test { public static void main(String... args) { try { Foobar foobar = new Foobar("Peter"); System.out.println("Name: " + foobar.getName()); Class<?> clazz = Class.forName("com.csa.mdm.Foobar"); System.out.println("Class: " + clazz); Field field = clazz.getDeclaredField("name"); field.setAccessible(true); String value = (String) field.get(foobar); System.out.println("Value: " + value); } catch (Exception e) { e.printStackTrace(); } } } class Foobar { private final String name; public Foobar(String name) { this.name = name; } public String getName() { return this.name; } }

或者,您可以使用类的 newInstance 方法在运行时获取对象的实例.不过,您仍然需要先设置该实例变量,否则它将没有任何值.

Or, you can use the newInstance method of class to get an instance of your object at runtime. You'll still need to set that instance variable first though, otherwise it won't have any value.

例如

Class<?> clazz = Class.forName("com.something.Foobar"); Object object = clazz.newInstance();

或者,在其构造函数中有两个参数,例如String和int ...

Or, where it has two parameters in its constructor, String and int for example...

Class<?> clazz = Class.forName("com.something.Foobar"); Constructor<?> constructor = clazz.getConstructor(String.class, int.class); Object obj = constructor.newInstance("Meaning Of Life", 42);

或者您可以在运行时使用 clazz.getConstructors()

Or you can interrogate it for its constructors at runtime using clazz.getConstructors()

注意,我特意省略了在此创建的对象的强制转换为预期的类型,因为那样会破坏反射的重点,因为如果您这样做的话,您已经知道该类了,这将不需要首先是反思.

NB I deliberately omitted the casting of the object created here to the kind expected, as that would defeat the point of the reflection, as you'd already be aware of the class if you do that, which would negate the need for reflection in the first place.

更多推荐

使用反射获取字段值

本文发布于:2023-07-09 14:30:10,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1086995.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   反射

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!