`
xly1981
  • 浏览: 142447 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

反射小计

    博客分类:
  • java
阅读更多
Test.java方法dd重载
class Test{
    public Test(){}
    
    public void dd(String s1,String s2){
        System.out.println(s1+":"+s2);
    }
    
    public void dd(String s1){
        System.out.println(s1+":");
    }
}


  public static void main(String ...strings) throws Exception{
        Class clazz = Class.forName("test.com.util.Test");
        
        Class[] parameterTypes = new Class[2];
        parameterTypes[0] = String.class;
        parameterTypes[1] = String.class;
        Method method = clazz.getMethod("dd", parameterTypes);//parameterTypes不同会取到不同的dd方法
        
        Object args[] = new Object[2]; 
        args[0] = new String("s1"); 
        args[1] = new String("s2"); 
        method.invoke(clazz.newInstance(), args);
        
        Class[] parameterTypes1 = new Class[1];
        parameterTypes1[0] = String.class;
        Method method1 = clazz.getMethod("dd", parameterTypes1);
        
        Object args1[] = new Object[1]; 
//Object args1[] = new Object[2]; //如果保留会报错IllegalArgumentException
        args1[0] = new String("s1"); 
//        args1[1] = new String("s2"); //如果保留会报错java.lang.IllegalArgumentException: wrong number of arguments
        method1.invoke(clazz.newInstance(), args1);
        }

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics