简体   繁体   中英

Change return value of an instance method

I would like to adjust the return value of a method from an instance class and I am not quite sure if it is possible with or without Reflection. I could not figure it out and so I wanted to ask it here. Lets say I have for example the following class Foo:

public final class Foo {
    
    public final String getName() {
        return "Foo";
    }
    
}

Some context:

  • Foo class is from an external library
  • Foo class is not adjustable
  • Foo class is not extendable

So with this basic example I would like to get Bar returned from the method getName() instead of Foo . To be very explicit:

Foo foo = new Foo();
String name = foo.getName();
System.out.println(name) //prints "Bar"

Why do I need this?

Well I need to pass this instance of Foo to another method which only accepts an object of the type Foo. This method will call the method getName() and will do some additional calculation.

Actual use case:

I will try to give more context, hopefully it will be a bit more clear. There is a method within a builder class which is accepting an instance of KeyManagerFactory a method called setKeyManagerFactory(KeyManagerFactory keyManagerFactory) . This builder class will internally call getKeyManagers on the KeyManagerFactory and it will return KeyManagers[]

The KeyManagerFactory is a final class, it doesn't have a public constructor at all. The getKeyManager method is also final. I already have a KeyManager[] and so I want to hack this KeyManagerFactory to return my own array own KeyManagers instead and supply it to the builder.

Since you said the intial class is final and cannot be instanciated, there is not much you can do.

From what i understand from this question , it might be possible to create a new class that would contains a Foo object with all of it's method. Then when you call a method from the newly created Bar class, you can call the same function on the parent. Except, of course, when it come to your getName function.

public final class Foo {
    
    public String getName() {
        return "Foo";
    }

    public String getBiz() {
        return "Biz";
    }
    
}

public class Bar {

   private Foo foo;

   public Bar() {
      this.foo = new Foo();
   }


   public String getName() {
      return "Bar";
   }

   public String getBiz() {
      return this.foo.getBiz();
   }
}


Bar bar = new Bar();
String name = bar.getName();
System.out.println(name) //prints "Bar"

String biz = bar.getBiz();
System.out.println(biz) //prints "Biz"

Notice here that the getBiz function of the bar object is only calling the getBiz function of the Foo object, not changing it's return value.

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