1

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

4
  • could you please rephrase your question? nothing will happen if you delete the function declaration assuming it's with 0 references Commented Oct 2, 2016 at 16:06
  • What do you mean by remove? What should happen if someone calls that method on that instance? Commented Oct 2, 2016 at 16:08
  • I'm voting to close this question as off-topic because this question clearly makes no sence. Commented Oct 2, 2016 at 16:08
  • 1
    This seems like an XY question. What are you trying to achieve with this approach? As the answers pointed out this is not possible without modifying the bytecode at runtime. Perhaps you can accomplish your goal with a less complicated approach? Commented Oct 2, 2016 at 16:13

2 Answers 2

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.