Re: how to get the return type of a Generic method
Sideswipe wrote:
Yeah, see this is the problem. I need to know what type WOULD be
returned without actually calling the function and returning it.
Basically, the problem is that I need to find compatible Comparables
based on this method. I kinda suspected I would need a class param but
I don't want to have to do it/make that case. It would be truly great
to KNOW things about the type T
You could start with Mark Space's suggestion and change the type bounds
somewhat. Let the compiler figure out the supertype; don't do it by hand.
<sscce>
package testit;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
/** SomePair - .
*/
public class SomePair <F extends Comparable<? super S>,
S extends Comparable<? super F>>
{
private final F first;
private final S second;
public SomePair( F f, S s )
{
this.first = f;
this.second = s;
}
public final F getFirst() { return first; }
public final S getSecond() { return second; }
public int compareFirstToSecond()
{
return first.compareTo( second );
}
/** Main method.
* @param args <code>String []</code> program arguments.
*/
public static void main( String[] args )
{
Integer a = 17;
Integer b = 19;
SomePair<Integer, Integer> sp =
new SomePair<Integer, Integer>( a, b );
System.out.println( "a = " + sp.getFirst()
+ ", b = " + sp.getSecond()
+ ", compare " + sp.compareFirstToSecond() );
java.sql.Date sd = new java.sql.Date( new java.util.Date().getTime() );
try
{
Thread.sleep( 1 );
}
catch ( InterruptedException ex )
{
}
java.util.Date ud = new java.util.Date();
SomePair<java.sql.Date, java.util.Date> dp =
new SomePair<java.sql.Date, java.util.Date>( sd, ud );
show( dp );
sd = new java.sql.Date( ud.getTime() );
dp = new SomePair<java.sql.Date, java.util.Date>( sd, ud );
show( dp );
}
private static final String DFS = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
private static final DateFormat DF = new SimpleDateFormat( DFS );
private static void show( SomePair<java.sql.Date, java.util.Date> dp )
{
System.out.print( "java.sql.Date " );
System.out.print( DF.format( dp.getFirst() ));
System.out.print( ", java.util.Date " );
System.out.print( DF.format( dp.getSecond() ));
System.out.print( ", compare " );
System.out.println( dp.compareFirstToSecond() );
}
}
</sscce>
--
Lew