The Artima Developer Community
Sponsored Link

Java Answers Forum
Type variables

4 replies on 1 page. Most recent reply: Mar 3, 2006 2:27 PM by Ravi Venkataraman

Welcome Guest
  Sign In

Go back to the topic listing  Back to Topic List Click to reply to this topic  Reply to this Topic Click to search messages in this forum  Search Forum Click for a threaded view of the topic  Threaded View   
Previous Topic   Next Topic
Flat View: This topic has 4 replies on 1 page
Makhmud Kasumov

Posts: 16
Nickname: marik
Registered: Oct, 2005

Type variables Posted: Mar 1, 2006 2:10 AM
Reply to this message Reply
Advertisement
Hi all!

I've got a class:
class A<T> {
  void test () {
    T t = new T();
  }
}


Compilator says that T cannot be instantiated directly. How can I create an object of type T then?


Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Type variables Posted: Mar 1, 2006 3:09 AM
Reply to this message Reply
Where is Class T?

Matthias Neumair

Posts: 660
Nickname: neumi
Registered: Sep, 2003

Re: Type variables Posted: Mar 1, 2006 4:02 AM
Reply to this message Reply
Forget my previous question.

Now that I did think about it it seems obvious that you can't create an instance because you class can't know which class T is.

You have to get a list all constructors from T and call one specific constructor.

I don't know how to accomplish this, I never tried.
But it should be similar to a get-class-by-name or get-method-by-name operation.

We allread y had a diskussion regarding that matter. Try looking for it, it could give you an idea.

Frank Sommers

Posts: 2642
Nickname: fsommers
Registered: Jan, 2002

Re: Type variables Posted: Mar 3, 2006 12:23 PM
Reply to this message Reply
This is a “good question.”

Ravi Venkataraman

Posts: 80
Nickname: raviv
Registered: Sep, 2004

Re: Type variables Posted: Mar 3, 2006 2:27 PM
Reply to this message Reply
The only way this can be done is if the class of T is known. Then, using a newInstance() on the class of T will get you a T object created using a no-args constructor. It is relatively easy to use reflection (java.lang.reflect.Constructor) to get a Constructor object of the known class of T with specified parametere types.

But why do you need to know the class of T when using parametrized classes? The whole point of the parametrized classes is that T is unknown until runtime! Hence, the parametrized classes can work with any type.

Flat View: This topic has 4 replies on 1 page
Topic: RMI question from Java Examples in a Nutshell Previous Topic   Next Topic Topic: Class URL

Sponsored Links



Google
  Web Artima.com   

Copyright © 1996-2019 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use