简单说,就是如何用invoke将a,b的值分别赋于同一个对象,再用其它方法调用a,b

解决方案 »

  1.   

    public class CSDN
    {
    public String a;
    public String b;
    public String sayHello()
    {
    return a+b;
    }
    public void setA(String s){
    a=s;
    }
    public void setB(String s){
    b=s;
    }
    public static void main(String a[])throws Exception
    {
    Object instance = Class.forName("CSDN").newInstance();
    Class k=Class.forName("CSDN");Method m = k.getMethod("setA", new Class[]{String.class});
    m.invoke(instance, new String[]{"Hello"});Method n = k.getMethod("setB", new Class[]{String.class});
    n.invoke(instance, new String[]{"World!"});
    n = k.getMethod("sayHello", new Class[]{});
    Object result= n.invoke(instance, new Object[]{});
    System.out.println(result);
    }
    }
      

  2.   

    <<
    虽然对a,b都进行了赋值,但m.invoke(p, args)的反回的对象却是不同的,一个returnObjectA,一个是returnObjectB
    那么如何在通过invoke调用sayHello()方法时,可以调用初始化好的a和b呢?
    >>
    ...介不废话嘛,你根本就没有用对还有没有看到你的p是哪里来得Class clazz = Class.forName("Hello");Hello hello = (Hello)clazz.newInstance();
    Method a = clazz.getMethod("setA", new Class[]{String.class});
    a.invoke(hello, new String[]{"hello, "});
    Method b = clazz.getMethod("setB", new Class[]{String.class});
    b.invoke(hello, new String[]{"buddy."});
    Method say = clazz.getMethod("sayHello", new Class[]{});
            
    TestCase.assertEquals("hello, buddy.", say.invoke(hello, null));