Alex Rivera | Logout

Java static members in a subclass accessed via a generic parent

Asked 2012-11-27T16:25:26.647
9

This seems like a newbish question, but the last time I worked with Java, the language didn't have generics. I have a class hierarchy (names changed to be as generalized as possible):

public abstract class AbstractBase { .... }
public class ConcreateSubA extends AbstractBase { .... }
public class ConcreateSubB extends AbstractBase { .... }
...
public class ConcreateSubZZ9PluralZAlpha extends AbstractBase { .... }
...

I'm trying to clean up some legacy code, and there's one place where a ton of repetitive duplication can all be factored out into a single routine via generics. (I'm thinking generics because when this routine is called, it needs to operate on only one of the concrete classes.)

The routine looks like

public <Thing extends AbstractBase> void someFunc()
{
    another_function_call (Thing.concreteSpecialToken);
    // could also be
    //   another_function_call (Thing.concreteSpecialToken());
    // if methods are more feasible than fields

    // Cannot use
    //   another_function_call (Thing().concreteSpecialToken());
    // because creating instances of these types is a Major Operation[tm]
}

I'm leaving out about a zillion lines, but that's the important part: someFunc() is type parametric (it actually takes arguments but none of them are Things so no inference). Eventually I need to fetch a special token and this is where I'm getting fuzzy.

The tokens are huge-ass unique strings for each concrete class. They're class-based, not instance-based. The actual token value is declared as a private static final field in each subclass.

So I need to use the public methods/fields of a base class to (eventually) get to the private static field of a subclass. Obviously I can't declare an abstract static method in the base, because that makes no sense. If the data were instance-based, then this would be trivial, with

Edit
Report

1 Answer

3

If I understand it correctly, you need the concrete class of the type parameter. The usual way of doing it is to declare your method like this: public <T extends AbstractBase> void someFunc(Class<T> clazz)

This of course means an extra parameter needs to be passed to the method and you need to use reflection to access the static fields, but given Java's type erasure it's the only way.

The moral of the story is that generics and statics don't go very well together.

answered 2012-11-27T16:32:30.200

Your Answer