简体   繁体   中英

How can I remove a method from the class definition on the fly?

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.

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.

Maybe you could use some wrapper or proxy that throws an exception once method is invoked.

Or Method.setAccessible(false);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM