0

I'm looking for a way in java to find all classes that belongs to a certain superclass, and within that class refer to a static string with a known name (using reflection?);

public class Bar
extends ObjectInstance
{
   public final static String Name = "Foo";

   // more 
}

From the example; there are n-occurences of classes that extend from ObjectInstance, and from all, i need the value of Name. The classes i am refering to are generated so i know for sure that there is a Name element that i can refer to, but i have no access to the generation sourcedata.

Bas Hendriks
  • 609
  • 1
  • 7
  • 14

2 Answers2

0

Perhaps the same question as How do you find all subclasses of a given class in Java?

This backs up my initial feeling that this can only be done like IDEs do it: by scanning everything down the tree, building your relationships as you go.

Community
  • 1
  • 1
0

No Way.

One failing solution:

publc abstract class ObjectInstance {

    public abstring String name();

    private static Map<String, Class<? extends ObjectInstance> klasses =
            new HashMap<>();

    protected ObjectInstance() {
        classes.put(name(), getClass());
    }

Only collects instantiated classes! So fails. With the idea to have the name provided by a function with return "foo";. Collecting the class.

There are two unsatisfactory solutions:

The other way around: use the name as a factory pattern:

enum Name {
    FOO(Bar.class),
    BAZ(Baz.class),
    QUX(Qux.class),
    BAR(Foo.class);

    public final Class<ObjectInstance> klass;

    private Name(Class<ObjectInstance> klass) {
        this.klass = klass;
    }
}

Maybe as factory to create instances too.

Using a class annotation, and have a compile time scanning:

@ObjectInstanceName("foo")
public class Bar extends ObjectInstance {
}

How to apply this to your case: experiment.

There would be a more fitting solution of using your own ClassLoader, but that is far too over-engineered.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138