• Post Reply Bookmark Topic Watch Topic
  • New Topic

Creating a generics class at runtime?  RSS feed

 
Neha
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

I want to create a generics class at runtime. Can I do that? So for example, I have

and I want to create a subclass of SuperClass with a Type that is determined at runtime, so something like this pseudocode:

Is this possible?

Thanks,
Neha.
[ December 27, 2007: Message edited by: Neha ]
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why wouldn't that just be

class SubClass extends SuperClass<Foo>

?

What are you trying to do?
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
"Neha", please check your e-mail for an important message from JavaRanch.
 
Rob Spoor
Sheriff
Posts: 21133
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Ilja Preuss:
Why wouldn't that just be

class SubClass extends SuperClass<Foo>

?

What are you trying to do?

It's not exactly the same - I think Neha tries to use the actual type, so the value returned by getClass(). This doesn't have to be Foo - it can be a subclass (or implementing class if Foo is an interface).


Generics are not actually used during runtime, they are only a compile time mechanism. Therefore, it is not possible to use the actual class of "foo".




Well ok, there is, but it involves creating the entire class from source during runtime using javax.tools.JavaCompiler or similar methods. That's something you REALLY don't want.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Rob Prime:

It's not exactly the same - I think Neha tries to use the actual type, so the value returned by getClass(). This doesn't have to be Foo - it can be a subclass (or implementing class if Foo is an interface).


Yes, I understand that he wants to do that. What I don't understand is *why* he would want to do that. I simply can't think of a scenario where it would make a difference.
 
Neha
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are right, Rob. Since generics is a compile time mechanism, it doesnt matter and I can create the class with Foo or a superclass/interface of Foo.

Thanks,
Neha.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!