iBelieve
iBelieve

Reputation: 1544

Applying static methods to data stored in a subclass

I'm working on a class to access information about a class library stored in a Jar file and run actions customized for each class library. It contains methods to load localized strings, etc. from the Jar file.

public class CodeBundle {
    public static String str(String id) {
        ...
    }

    ...
}

I need to be able to know which library I am trying to load information from, so I want to be able to use subclasses representing each library, for example:

public class JAppFramework extends CodeBundle {
    ...
}

So now in code that is part of the JApp Framework, I want to be able to call JAppFramework.str("...") to load a string from the JApp Framework resource bundle. And if I have another library, such as TestLibrary, I want to be able to call TestLibrary.str("...") to load a string from Test Library's resource bundle. What I did was have a method defined in CodeBundle called getFile() which would return the Jar file from which the library had been loaded. Then the str() method would use that to load the localized string.

The problem is that the static methods in CodeBundle can only access data stored in the CodeBundle class, not in any of its subclasses, as far as I know.

For various reasons, I can't use "getClass().getResource(name)" to load resources.

Is there any way to do what I'm trying to do?

Upvotes: 0

Views: 52

Answers (1)

fge
fge

Reputation: 121710

You may try and use singletons:

public abstract class CodeBundle { // or even an interface
    public abstract String str(String id);
}

public final class JAppFramework extends CodeBundle {
    private static final CodeBundle INSTANCE = new JAppFramework();

    // private constructor
    private JAppFramework() {
        // whatever
    }

    // get the instance
    public static CodeBundle getInstance() { return INSTANCE; }

    // Implement str() here
}

// Create other singletons as needed

In your code:

CodeBundle bundle = JAppFramework.getInstance();
bundle.str(whatever);

Of course, this is an ultra simplistic example. Put whatever fields/methods/constructors/constructor arguments are needed in CodeBundle -- which cannot be instantiated since it is abstract.

Upvotes: 1

Related Questions