package test;
public class GenericUsage {
/**
* 测试范型编程。
*
* @param <T>
* @param E
* @return
* @throws InstantiationException
* @throws IllegalAccessException
*/
public <T> T getObject(Class<? extends T> E) throws InstantiationException,
IllegalAccessException {
return E.newInstance();
}
}
package test;
import junit.framework.TestCase;
public class GenericUsageTest extends TestCase {
GenericUsage gu = new GenericUsage();
public void testGetObject() throws InstantiationException,
IllegalAccessException {
String str = gu.getObject(String.class);
assertNotNull(str);
}
}
例子中的方法,返回值是在运行时传入的。