Ryan
Ryan

Reputation: 2886

Using reflection to modify the structure of an object

From wikipedia:

reflection is the ability of a computer program to examine and modify the structure and behavior (specifically the values, meta-data, properties and functions) of an object at runtime.

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?

Upvotes: 4

Views: 2592

Answers (4)

Dan
Dan

Reputation: 11183

In English reflection means "mirror image".

So I'd disagree with the Wikipedia definition. For me, reflection is about runtime inspection of code, not manipulation.

In java, you can modify the bytecode at runtime using byte code manipulation. One well known library and in wide spread use is CGLIB.

Upvotes: 2

Diversity
Diversity

Reputation: 1900

Just an additional hint since the previous answers and comments answer the question concerning reflection. To really change the structur of a class and therefore its behaviour during runtime look at Byte code instrumentaion and in this case javassist and asm libs. In any case this is not trivial task.

Additionally you might have a look at aspect programming technic, which enables you to enhance methods with some functionallity. Often used to introduce logging without the need to have a dependency of the logging classes within your class and also dont have the invocations of the logging methods between the problem related code.

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

The only method in reflection (java.lang.reflect) to modify object's class behaviour is to change the accessibility flag of Constructor, Method and Field - setAccessible, whatever wiki says. Though there are libraries like http://ru.wikipedia.org/wiki/Byte_Code_Engineering_Library for decomposing, modifying, and recomposing binary Java classes

Upvotes: 1

GeertPt
GeertPt

Reputation: 17846

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

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

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 is still a static typed language, unlike javascript where you can change any behaviour at runtime.

Upvotes: 1

Related Questions