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

A

Aryeh.Friedman

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
 
O

Oliver Wong

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?)

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top