class.forName()用法心得---动态加载类 和调用类的方法和属性的方法


#007 Class c = Class.forName("Test");
#008 Class ptypes[] = new Class[2];
#009 ptypes[0] = Class.forName("java.lang.String");
#010 ptypes[1] = Class.forName("java.util.Hashtable");
#011 Method m = c.getMethod("func",ptypes);
#012 Object obj=c.newInstance();//原文是“ Test obj = new Test();”我觉得原文违背了动态加载

                 //的本意 所以修改成了“Object obj=c.newInstance();//”
#013 Object args[] = new Object[2];
#014 arg[0] = new String("Hello,world");
#015 arg[1] = null;
#016 Object r = m.invoke(obj, arg);
#017 Integer rval = (String)r;
#018 System.out.println(rval);
#019 }

以上为网上找的资料。我发现要在实际中应用 还有许多知识点 需要补充:

以上很多函数必须进行异常处理,所以以上代码要放在try语句内 同时有相应的catch语句。

我的一段完整的代码如下:

String Classname="yourPackage.YourClassname";
         
    try {
         Class tt=Class.forName(Classname);//动态获得class,假设此处
     Object t=tt.newInstance(); //得到tt的实例对象
      Class[] ptypes = new Class[1];//方法的1个参数类型 

      ptypes[0] = Class.forName("java.lang.String");
      Method SF = tt.getMethod("method1",ptypes);//定义方法对象  

      Object[] arg = new Object[1];//方法的参数为1个
      arg[0] = "YourString";
      SF.invoke(t,arg);//动态调用t.method1(String str)方法 
       ptypes[0] = Class.forName("java.lang.Integer");
       Method SC = tt.getMethod("setIcount",ptypes);//定义方法对象      
       arg[0] = new Integer(1);
       SC.invoke(t,arg);//动态调用setIcount(int)方法 
        ptypes[0] = Class.forName("java.lang.Integer");
        Method SCH = tt.getMethod("setIchoosecount",ptypes);//定义方法对象    
        arg[0] = new Integer(2);
        SCH.invoke(t,arg);//动态调用setIchoosecount(int)方法

  
         Method FZ = tt.getMethod("method2");//定义方法对象
         FZ.invoke(t); //动态调用无参数方法t.method2()
       
       } catch (InstantiationException e) {
          e.printStackTrace();
       } catch (IllegalAccessException e) {
          e.printStackTrace();
      } catch (ClassNotFoundException e) {
         e.printStackTrace();
     }catch (NoSuchMethodException e) {
           e.printStackTrace();
     }catch(InvocationTargetException e) {
     e.printStackTrace();
      } //用类名实例化一个对象t并调用他的方法。
    注:我还有一个问题没有搞清楚,如果你知道请告诉我答案:

method的invoke(object objectname,object[] args)

如果被动态加载的方法参数不是 object类型的 而是原始类型 如int double 的 怎么办呢?

 

你可能感兴趣的:(java)