Tag Archives: gernic

[Java generic] Class Literals as Run-time Type Tokens



Collection emps =
sqlUtility.select(EmpInfo.class, ”select * from emps”);
...
public static <T> Collection<T> select(Class<T>c, String sqlStatement) {
	Collection<T> result = new ArrayList();
	/* run sql query using jdbc */
	for ( /* iterate over jdbc results */ ) {
		T item = c.newInstance();
		/* use reflection and set all of item’s fields from sql results */
		result.add(item);
	}
		return result;
}




public static <T> T writeAll(Collection<T> coll, Sink<? super T> snk){
	T last;
	for (T t : coll) {
		last = t;
		snk.flush(last);
	}
	return last;
}

Sink<Object> s;
Collection<String> cs;
String str = writeAll(cs, s);



class Foo implements Comparable<Object> {...}
...
Collection<Foo> cf = ...;
Collections.max(cf); // should work

public static <T extends Comparable<? super T>>
T max(Collection<T> coll)


 

In general, if you have an API that only uses a type parameter T as an argument, its
uses should take advantage of lower bounded wildcards (? super T). Conversely, if
the API only returns T, you’ll give your clients more flexibility by using upper bounded
wildcards (? extends T).