Skip to content
Advertisement

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:

JavaScript

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:

JavaScript

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.

Normally the KeyManagerFactory is instantiated with the following snippet:

JavaScript

With the above snippet the KeyManagerFactory will return a KeyManager array based on the provided KeyStore object. What I want to achieve is to somehow return my custom KeyManager array.

I also added the decompiled source code of the KeyManagerFactory:

JavaScript

Advertisement

Answer

I was able to accomplish what I wanted with the hint of @tgdavies. Thank you!

So what I did was I created a KeyManagerFactoryWrapper which contains a custom KeyManagerFactorySpi called KeyManagerFactorySpiWrapper.

JavaScript

I was able to achieve the same with the TrustManagerFactory:

JavaScript

Now I can easily create a the KeyManagerFactory and TrustManagerFactory with the following snippet:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement