Jump to content


Java Generics


4 replies to this topic

#1 Teron

    Absinth drinker

  • Member
  • 938 posts

Posted 15 October 2008 - 16:59

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.

"It's not the cards you have, it's how you play them!" - Gambit (X-Men)

#2 CodeCat

    It's a trap!

  • Gold Member
  • 6111 posts

Posted 15 October 2008 - 17:33

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).
CodeCat

Posted Image
Posted Image

Go dtiomsaítear do chód gan earráidí, is go gcríochnaítear do chláir go réidh. -Old Irish proverb

#3 Teron

    Absinth drinker

  • Member
  • 938 posts

Posted 15 October 2008 - 17:44

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.

"It's not the cards you have, it's how you play them!" - Gambit (X-Men)

#4 CodeCat

    It's a trap!

  • Gold Member
  • 6111 posts

Posted 15 October 2008 - 19:52

What about just using Class<T> instead?
CodeCat

Posted Image
Posted Image

Go dtiomsaítear do chód gan earráidí, is go gcríochnaítear do chláir go réidh. -Old Irish proverb

#5 Teron

    Absinth drinker

  • Member
  • 938 posts

Posted 15 October 2008 - 21:30

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.

"It's not the cards you have, it's how you play them!" - Gambit (X-Men)



1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users