dimanche 20 décembre 2020

Adjust return value of a method which is a singleton and has final access modifiers

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 {

    private static final INSTANCE = new Foo("Foo")

    private String name;

    protected Foo(String name) {
        this.name = name;
    }
    
    public final String getName() {
        return name;
    }

    public static Foo getInstance() {
        return INSTANCE;
    }
    
}

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 = Foo.getInstance();
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.





Aucun commentaire:

Enregistrer un commentaire