lapots
lapots

Reputation: 13395

change java class in runtime

I've got a class with number of fields.

class MyClass {
    private String field1;
    private String field2;
}

Is it possible to change the name of the field using reflection? (for example to transform field1 into field0 and etc.)

Upvotes: 2

Views: 122

Answers (1)

Stephen C
Stephen C

Reputation: 718796

Is it possible to change the name of the field using reflection?

No.

The closest you can get to this1 is to change the source code, recompile, and then create a new classloader to load the new class.

But beware that what you will have is a different class to the one that you started with:

  • Instances of the old class won't acquire the new field.

  • Code that was loaded at the same time as the old class will continue to be bound to the old class.


1 - You can achieve the same effect using "byte code engineering", but you still need to load the class again, and the caveats still apply.

Upvotes: 2

Related Questions