2

I saw Java examples that use reflection to change values of member variable from outside of the class at run time. It may be done for private and even final fields. May be there is a way to add a field to a class at run time using reflection ?

I found very similar question: Can a Java class add a method to itself at runtime?

The answer is yes, it is possible using custom class loaders or byte code manipulation tools.

  • Not with documented APIs. You should also be careful with reflection and access to private members. Since Java 10 and the introduction of modules, reflection has to play by the visibility modifiers (`private`, `protected`, ``). – Turing85 Jun 03 '18 at 15:10
  • As I understood a bit more by now I would like to say that we should distinguish Java language where adding field at runtime has no sense from Java machine implementation. Java machine may add fields for its' own uses like garbage collection, optimization and debugging. I don't know details but custom class loader can do some of these changes. There is a JRE parameter to use custom class loader: java -Djava.system.class.loader=myClassLoader –  May 19 '20 at 16:34

3 Answers3

1

That is impossible, in fact the idea of "adding fields at run-time" doesn't even make sense. Java is a static language, which means for your code to compile, type information for all class fields has to be known at compile-time, which means those fields have to exist at compile time. If you create a class like

class Person {
    String name;
    int age;
}

and then somewhere in your code, you reference person.height, your code will not even compile, because the height field does not exist. So even if you could add the height field at run-time, what's the point when your code won't even compile in the first place? That's why I say it's not possible.

Leo Aso
  • 11,898
  • 3
  • 25
  • 46
0

As far as I know, the answer is no. Reflection should reflect the data and not modify it.

sharon182
  • 533
  • 1
  • 4
  • 19
  • I disagree with generality of this statement. if reflection was designed to only read class info, why would Java have methods to write it as well? I think there should be blessed and legitimate use for that. –  Jun 03 '18 at 15:57
0

Using reflection: NO But possible to add behavior to some extent using design patterns.

Refer to the below document. link

I hope this will be of some help for you.