Adding methods to exists class in android

android, design-patterns, java

Solution

You could create a utility class with static methods:

public final class ProviderUtils {

    private ProviderUtils() {} // not instantiable, it is a utility class

    public static void print(Provider provider) {
        String name = provider.getName();
        // print the name
    }
}

In your code, you can then call it:

Provider p = new Provider(...);
ProviderUtils.print(p);

And if that class only has one `print` method, you can maybe call it `ProviderPrinter` instead of `ProviderUtils`.

In the end you don't have thousands of possibilities - you can:

- extend the class and whatever method you need in the sub class => you said you don't want that

- modify the source code of the class and recompile your own version of the jar

- wrap the class in a wrapper that adds the methods you need (your ProxyProvider example)

- put the methods you need in a static utility class (what I proposed above)

- modify the class at runtime and add a method, but that's a complicated path because you need to play with classloaders.

Problem

I'm looking for a way to add some methods into exists class like this: ``` String s = ""; s.doSomething(); ``` In objective C, I can use category to do this. ``` @interface NSString( Stuff) -(void)doSomething(); @end ``` Is android has something like that? Or another hack? Update: Actually, I got this problem: I use a class (not final) from jar file (so, I can't touch its source code). Then I want to add methods( or something like that) into this class without using inheritance. For example: ``` public class Provider{ // many methods and fields go here... public String getName(){} } ``` All I want to do is: ``` provider.print(); //that call getName() method; ``` I also tried proxy pattern, it worked, but I don't like that way (because it like a wrapper class, I must store an object with many fields and methods to use only one method): ``` public class ProxyProvider{ Provider provider; public ProxyProvider(Provider provider){ this.provider = provider; } public void print(){ String name = provider.getName(); //do something } } ``` Is there any way to solve that?

Original source

Related problems