简体   繁体   中英

Can I remove a method from a class instance in java?

Lets say I have a class called 'Foo', with some methods:

 public class Foo{
    public void a(){
       //stuff
    }

    public void b(){
       //stuff
    }
 }

And i have an instance of Foo: Foo instanceOfFoo = new Foo();

Can i remove the method 'a' from 'instanceOfFoo'?

You can't remove a method, not without changing the byte code and breaking the code's "contract", but you could extend the class and have the child class's method override throw an UnsupportedOperationException if called. Also the child class should deprecate the method, and explain in its javadoc the rationale behind it, and what to use in its place.

This would change the class's contract, but in a more responsible way then say fiddling with the byte code.

For example:

public class Foo {
    public void a() {
        // stuff
    }

    public void b() {
        // stuff
    }
}

public class FooChild extends Foo {
    /**
     * @deprecated: This method should no longer be used and will throw an exception
     */
    @Override
    @Deprecated
    public void a() {
        String text = "The method a is no longer supported";
        throw new UnsupportedOperationException(text);
    }
}

Short answer: No, not really.

Long answer: If you can control the ClassLoader being used to load the Foo class, you can intercept the request to load the Foo class and use ASM or Javassist to modify the class's bytecode before loading it.

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