private void doSomething <T> (String msg) {
T.say(msg);
}
我的意思很简单,通过T来动态确定类型,可是上面的语句不能通过。
方法申明都不能通过,为何呢?应该如何作呢?
------解决方案--------------------
package edu.zsu.zouang.test;
import java.text.DecimalFormat;
import java.text.ParseException;
public class MyTest <T extends sayInterface> {
private Class <T> type;
public MyTest(Class <T> type){
this.type = type;
}
private void doSomething(String msg){
try {
type.newInstance().say(msg);
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
static class Test implements sayInterface{
public void say(String msg) {
// TODO Auto-generated method stub
System.out.println(msg);
}
}
public static void main(String[] args){
MyTest test = new MyTest(Test.class);
test.doSomething( "Hello ");
}
}
sayInterface的接口定义:
package edu.zsu.zouang.test;
public interface sayInterface {
public void say(String msg);
}