“`” 考察点:类

可以通过类对象的getDeclaredField()方法字段(Field)对象,然后再通过字段对象的setAccessible(true)将其设置为可以访问,接下来就可以通过get/set方法来获取/设置字段的值了。下面的代码实现了一个反射的工具类,其中的两个静态方法分别用于获取和设置私有字段的值,字段可以是基本类型也可以是对象类型且支持多级对象操作,例如ReflectionUtil.get(dog, “”owner.car.engine.id””);可以获得dog对象的主人的汽车的引擎的ID号。

`import` `java.lang.reflect.Method;``class` `MethodInvokeTest {``  ``public` `static` `void` `main(String[] args) ``throws` `Exception {``    ``String str = ``""hello""``;``  ``Method m = str.getClass().getMethod(``""toUpperCase""``);``    ``System.out.println(m.invoke(str)); ``// HELLO``  ``}``}`
            "```

Was this helpful?

0 / 0

发表回复 0

Your email address will not be published.