Generics in static fields

Hi, I am trying to make a class which has some generic fields. I understand that it would not work just like that as the compiler has no way what the generic fields should actually be in a static context.

I want to use the generic class as an abstract class which would be extended, so that way the generics should be resolvable. Is there any way to make this work this way or should I not use generics and go type unsafe?

This is what I want to do in code:

abstractclass ClassToBeExtended<A>

{

static A a;

}

class UsingTheOtherextends ClassToBeExtended<String>{}

[896 byte] By [SavageNLDa] at [2007-11-27 8:26:49]
# 1

Why need it be static, though? This doesn't make sense, since you'd need to instantiate your class in order to assign an actual type to the type variable 'A', and by definition a static field would exist independently of any instance. What you could do is have a static field of the most generic type applicable to A, if you really want a static field

public abstract class MyClass<A extends SomeOtherClass> {

static SomeOtherClass a;

// stuff

}

depends on your needs. Why d'you need this static field to be generic?

georgemca at 2007-7-12 20:16:22 > top of Java-index,Java Essentials,New To Java...
# 2

It is supposed to be a class that adds relations between other classes:

// Simplified

class RelationBetweenAandB extends TheClass<A, B> {}

class SomeOtherClass

{

void foo()

{

A a = new A();

B b1 = new B();

B b2 = new B();

RelationBetweenAandB.add(a, b1);

RelationBetweenAandB.add(a, b2);

new YetAnotherClass().listRelationsOf(a);

}

}

class YetAnotherClass

{

public void listRelationsOf(A a)

{

for (B b : RelationBetweenAandB.allRhs(a))

; // Iterate through b1 and b2

}

}

Having static fields will make the relation useful from anywhere in the application, if it is not static then all the objects that are going to be used in a relation have to instantiate the class which wlll probably introduce a lot of overhead.

abstract class SomeClass<A extends OtherClass>

{

static OtherClass a;

}

Would require me to have Object in stead of OtherClass because I want all types of object to be in a relation, which is what I meant by going type unsafe :)

Message was edited by:

SavageNLD

Added some more reasoning about why I want static fields

SavageNLDa at 2007-7-12 20:16:22 > top of Java-index,Java Essentials,New To Java...