←  Code Block

Fallout Studios Forums

»

Java Generics

Teron's Photo Teron 15 Oct 2008

Is there a way to get the given class type of a generic class by a functioncall?

Like, for example, you have the following:

public class House<T> {

 private Class<?> clazz;

 public House&#40;&#41; {
  this.clazz = this.getTypeOfClass&#40;&#41;; //needs implementation, but how?
 }

}


What I don't want to use is the instanceof call, because "T" can be nearly anything.
Edited by Teron, 15 October 2008 - 17:00.
Quote

CodeCat's Photo CodeCat 15 Oct 2008

No matter what T can be, instanceof will work, because any T you use is guaranteed to be an object that instanceof will work on. Java generics work only on objects, unlike C++ templates which work on anything at all (even built-in types).
Quote

Teron's Photo Teron 15 Oct 2008

Yes, but the instanceof call checks for a given argument, but it is not commendable to check for nearly 100 classes with it. As said, T can be any type and that's my problem. ;)

I found a workaround, but perhaps there's another way to do so and that's what I'm asking here for ^^

Workaround:
public class House<T> {

private Class<?> clazz;

public House&#40;Class clazzToSet&#41; {
  this.clazz = clazzToSet;
}

}


But as you can see, I lacks of typechecking. (clazzToSet can differ from T)
Edited by Teron, 15 October 2008 - 17:47.
Quote

CodeCat's Photo CodeCat 15 Oct 2008

What about just using Class<T> instead?
Quote

Teron's Photo Teron 15 Oct 2008

Yeah, you're right. That's even better.
The problem still remains, though and will not be acceptable in later versions of my application, because the class mentioned above (and many others) will implement a common interface. But it isn't possible to overwrite/set the standard constructor in an interface to force a parameter. (because an interface never declares a constructor)

So the situation is:
Either I have to force the alternative constructor to be used/set over an Interface (but how, if it's even possible?), or I have to find/implement a method which returns the current class T.
Edited by Teron, 15 October 2008 - 21:31.
Quote