读书人

怎么将一个类对象转化成另一个Interfa

发布时间: 2012-05-20 16:03:12 作者: rapoo

如何将一个类对象转化成另一个Interface
现在有个接口 public interface Test{ pubic int ss;}
一个类继承这个接口 pubic class Testclass implement Test{}
有一个类 public class Testlocal{
public void setTest(Test test){ }
}

public static testrun(Obect ob){
String classname="com.test.Testlocal";
Class classlocal=Class.forName(classname);
Object local=classlocal.newInstance();
Method setinfo=classloal.getMethod("setTest",Class.forName("com.test.Test"));
setinfo.invoke(local,ob);

}


但是 ob 是com.test.Testclass 类型的 直接运行 报 argument type match

求高手 解决

[解决办法]

Java code
import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;interface Test {}class Testclass implements Test {}public class Testlocal {    public void setTest(Test test) {        System.out.print("Hello World!");    }    public static void testRun(Object ob) throws ClassNotFoundException,            InstantiationException, IllegalAccessException, SecurityException,            NoSuchMethodException, IllegalArgumentException,            InvocationTargetException {        String classname = "Testlocal";        Class classlocal = Class.forName(classname);        Object local = classlocal.newInstance();        Method setinfo = classlocal.getMethod("setTest",                Class.forName("Test"));        setinfo.invoke(local, ob);    }    public static void main(String args[]) throws SecurityException,            IllegalArgumentException, ClassNotFoundException,            InstantiationException, IllegalAccessException,            NoSuchMethodException, InvocationTargetException {        testRun(new Testclass());    }}
[解决办法]
Java code
interface Test {    public int ss = 1;;}class Testclass implements Test {}public class Testlocal {    public void setTest(Test test) {        System.out.println("ABC");    }    public static void testrun(Object ob) throws Exception {        String classname = "testNew.Testlocal";        Class classlocal = Class.forName(classname);        Object local = classlocal.newInstance();        Method setinfo = classlocal.getMethod("setTest", Class.forName("testNew.Test"));        setinfo.invoke(local, ob);    }    public static void main(String[] args) throws Exception{        testrun(new Testclass());    }} 

读书人网 >J2SE开发

热点推荐