动态拼接方法执行,反射强大的反射

来源:互联网 发布:淘宝福袋真的不能退吗 编辑:程序博客网 时间:2024/05/29 07:48

想动态执行方法么 ,别急用反射

import java.lang.reflect.Method;
 
public class sssss {
 
    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {
        // System.out.print( "ssss ".toUpperCase());
        String bb = "item1";
        // System.out.print(bb.substring(0,1).toUpperCase()+bb.substring(1,bb.length()));
 
        String aa = "get" + bb.substring(01).toUpperCase()
                + bb.substring(1, bb.length());
        Class<sssss> classType = sssss.class;
 
        Method method = classType.getMethod(aa, null);
        method.invoke(classType, null);
    }
 
    public static void getItem1() {
 
        System.out.print("ddddddddddd ");
    }
 
    public static void getItem2() {
 
        System.out.print("ddddddddddd ");
    }
}


使用反射执行一个方法时常遇到object is not an instance of declaring class的异常

决办法如下:

 第一种:反射执行的方法 getPrimaryKey() 改成静态的

第二种:在执行方法前先实例化类。m.invoke(mothed,null)改为m.invoke(c.newInstance(),null)或者m.invoke(new PrimaryKeyUtils(),null)



  1.  public String GetPrimaryKey(String mothed){  
  2.         String primaryKey = "";  
  3.         try {  
  4.             Class c = PrimaryKeyUtils.class;  
  5.             Method m = c.getMethod(mothed,new Class[]{});  
  6. //          Object obj=c.newInstance();  
  7.             m.invoke(mothed,null);  
  8.             primaryKey = String.valueOf(m.invoke(c.newInstance() ,new Object[]{}));  
  9.         } catch (Exception e) {  
  10.             e.printStackTrace();  
  11.         }   
  12.         return primaryKey;  
  13.     }  



原创粉丝点击