Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / November 2005

Tip: Looking for answers? Try searching our database.

returin a generic if there is no reference to it in the param list

Thread view: 
Aryeh.Friedman@gmail.com - 14 Nov 2005 18:40 GMT
Maybe I missing something obvious but there seems to no way to do
somehting like this (yes I know the syntex is illegal):

foo<Integer>()

public <T> T foo()
{
     return ack(T this);
}

assume ack returns some instance of T...

How do I pass the type param to to foo?.... everything in the generics
tutorial implies that either it must be defined when the instance is
made and/or T x must be a param:

public Foo<T>
{
  public T foo()
  {
      return ack(this);
  }
}

or

public class Foo
{
     public <T> T foo()
     {
          return ack(this);
     }
}

This would be ok except if foo() is static there is no actual instance
of Foo (it contains nothing but static methods and the default/only
constructor is private).   How do set T at run time (syntatically?)

--Aryeh
Oliver Wong - 14 Nov 2005 19:44 GMT
> Maybe I missing something obvious but there seems to no way to do
> somehting like this (yes I know the syntex is illegal):
[quoted text clipped - 33 lines]
> of Foo (it contains nothing but static methods and the default/only
> constructor is private).   How do set T at run time (syntatically?)

   If the "foo" method is static, you should actually show that in your
example, otherwise you may confuse the people who are trying to help you.

   If you're using Eclipse to compiler your code, the code you posted
should work. Eclipse can use the return type to infer the parameterize type.
If you're using Sun's compiler, you have to give a hint as to what the type
is. The typical way of doing that is to pass the type in as a class.

<code>
public <T> T foo(Class<? extends T> clazz) {
 return clazz.cast(ack(this));
}

public void someMethodThatUsesFoo() {
 String myString = foo(String.class);
}
</code>

   - Oliver


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2009 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.