nickkoro
nickkoro

Reputation: 394

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'?

Upvotes: 1

Views: 1472

Answers (2)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

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);
    }
}

Upvotes: 2

Shadowfacts
Shadowfacts

Reputation: 1053

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.

Upvotes: 2

Related Questions