Question

This is just a learning experiment for fun. I'm toying with bytecode manipulation.

I'm just messing around for learning with asm in java. I wonder if it is possible to replace the return type of a method from an interface.

Let's say that I have an interface:

interface Modifiable {
    Integer a();
}

Should I create a copy of the class, load it into the class loader, and then modify this new interface?

If it were possible, this change would be available in compile time? So to speak, that my ide autocomplete those new methods.

Was it helpful?

Solution

You can't change the return type without changing the interface itself.

OTHER TIPS

You have to change the interface itself.

It´s not possible to change the return type of a Method at runtime.

I want to change the return type to Boolean. Is this possible?

You can change the text from Integer to Boolean.

You can do this at runtime, but it would make the interface unusable unless all the implementations were changed.

Should I create a copy of the class, load it into the class loader, and then modify this new interface?

If you like, but I don't see the point.

If it were possible, this change would be available in compile time?

Yes, change the word from Integer to Boolean. Much easier to do in your IDE.

In compile time you definitely cannot change the return type of a method. And in runtime, yes it is possible. But that is not a good idea at all. Below guide line from asm, might help you

You must either return the replacement method/field when you visit the original one using a ClassVisitor, or you must first remove the original method/field in the ClassVisitor (see "1. How do I remove a method/field?"), and then add the new method/field by calling a visit method on the ClassWriter.

The problem that I see is that who ever is using the Object that implements Modifiable will be expecting an Integer to be returned when that method is called. You are breaking a promise that has been made by the creator of this interface.

You could of course create your own class that extends the type being returned by the interfaced method. I do not recommend this for something like Integer, because there will be many ways Integer may be used but it is technically possible.

Well as far as I know, it can't be done at runtime. but you can use generics to do that.

in your example, do it like

interface Modifiable<T> {
    T a();
}

where T will be your type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top