日期:2014-05-20 浏览次数:20679 次
String s = "HelloWorld"; Object o = someMethod(); ((HelloWorld)o).sayHello(s);
------解决方案--------------------
package com.train.first;
import java.lang.reflect.Method;
public class Test
{
public static void main(String[] args) throws Exception
{
String clazz = "Hello";
Object obj = getHello();
if (null == obj)
{
return;
}
Class c = obj.getClass();
if (c.getInterfaces().length > 0)
{
for (int i = 0; i < c.getInterfaces().length; i++)
{
if (clazz.equals(c.getInterfaces()[i].getSimpleName()))
{
Method m = c.getMethod("sayHello", new Class[]{String.class});
m.invoke(obj, "God");
break;
}
}
}
}
private static Object getHello()
{
return new HelloImpl();
}
}
interface Hello
{
public void sayHello(String name);
}
class HelloImpl implements Hello
{
public void sayHello(String name)
{
System.out.println("Hello, " + name);
}
}