使用反射来修改对象的结构

使用反射来修改对象的结构

本文介绍了使用反射来修改对象的结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

来自维基百科:

反射是计算机程序在运行时检查和修改对象的结构和行为(特别是值、元数据、属性和函数)的能力.

谁能给我一个修改对象结构的具体例子?我知道以下示例.

Can anyone give me a concrete example of modifying the structure of an object? I'm aware of the following example.

Object foo = Class.forName("complete.classpath.and.Foo").newInstance();
Method m = foo.getClass().getDeclaredMethod("hello", new Class<?>[0]);
m.invoke(foo);

获取类和检查结构的其他方法.但问题是如何进行修改?

Other ways to get the class and examine structures. But the questions is how modify is done?

推荐答案

在 Java 中,维基百科定义的反射并不完全支持.

In java, reflection is not fully supported as defined by the wikipedia.

只有 Field.setAccessible(true)Method.setAccessible(true) 真正修改了一个类,但它仍然只改变了安全性,而不是行为.

Only Field.setAccessible(true) or Method.setAccessible(true) really modifies a class, and still it only changes security, not behaviour.

框架,例如hibernate 使用它来向类添加行为,例如在字节码中生成访问父类中私有字段的子类.

Frameworks like e.g. hibernate use this to add behaviour to a class by e.g. generating a subclass in bytecode that accesses private fields in the parent class.

Java 仍然是一种静态类型语言,与 javascript 不同,您可以在运行时更改任何行为.

Java is still a static typed language, unlike javascript where you can change any behaviour at runtime.

这篇关于使用反射来修改对象的结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 18:17