Reputation: 7226
Let me start by saying that this is purely an exercise to satisfy my curiosity. This is not meant to be used in any sort of production environment.
What I would like to know is if it is in any way possible to redefine a class on the fly by removing/adding methods to its definition.
For example, given this class:
public class PersonBuilder {
private String name;
private int age;
public PersonBuilder name(String name) {
this.name = name;
System.out.println("Name defined");
return this;
}
public PersonBuilder age(int age) {
this.age = age;
System.out.println("Age defined");
return this;
}
}
What I want is to completely remove name
from the class definition once it is invoked. Equivalent behavior is expected if I invoke age
. Basically whichever method is invoked gets removed.
I understand this would require some level of bytecode manipulation, I'm fairly certain it cannot be achieved via reflection.
Anyway, I am looking for some guidance on how I could develop such behavior. Any tips will be very helpful.
Upvotes: 1
Views: 183
Reputation: 306
Maybe you could use some wrapper or proxy that throws an exception once method is invoked.
Or Method.setAccessible(false);
Upvotes: 0
Reputation: 20455
The problem is that even you find a way to do what you want (it is certainly possible) the code that call that methods is already compiled. This mean only practical outcome will be NoMethodDefFound
exception at moment when method will be called second time.
So my solution is to create counter for method and check it each time you call this method. Throw exception when you called second time.
Of course this will not work with reflection.
Upvotes: 3