posts - 12,  comments - 2,  trackbacks - 0
          Java 中,無論生成多個(gè)類的對象,這些對象都會對應(yīng)于同一個(gè)Class對象

          2.獲取某個(gè)類或某個(gè)對象所對應(yīng)的Class對象常用的3種方式
          a)使用Class類的靜態(tài)方法forName:Class.forName("java.lang.String")
          b)使用類語法String.class
          c)使用對象的getClass()方法:String s ="aa";
          Class<?> clazz= s.getClass(); 
            不帶參數(shù)的構(gòu)造方法,生成對象
           a)先獲得Class對象,然后通過Class對象newInstance() 方法直接生成對象。
           b) 先獲得Class對象,然后通過該對象獲得對應(yīng)的Construtor 對象,

          package com.doodoosun;

          import java.lang.reflect.InvocationTargetException;
          import java.lang.reflect.Method;

          public class ReflectTest {


              
              public int add (int param1,int param2){
                  return param1+param2;
              }
              
              public String echo (String message){
                  return "Hello :"+message;
              }
              
              
              public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, SecurityException, IllegalArgumentException, InvocationTargetException {
                  // TODO Auto-generated method stub
                  Class<?> classType = ReflectTest.class;
                  
                  Object reflectTest = classType.newInstance();
                  
                  Method addMethod = classType.getMethod("add",new Class[]{int.class,int.class});

                  Object result = addMethod.invoke(reflectTest,new Object[]{1,2});
                  
                  System.out.println("-------"+(Integer)result);
                  
                  Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
                  
                  Object result2  = echoMethod.invoke(reflectTest, new Object[]{"tom"});
                  
                  System.out.println(result2);
                  
                  
                  
              }
          posted on 2014-12-02 00:50 doodoosun 閱讀(145) 評論(0)  編輯  收藏 所屬分類: Java 相關(guān)

          <2025年5月>
          27282930123
          45678910
          11121314151617
          18192021222324
          25262728293031
          1234567

          常用鏈接

          留言簿(1)

          隨筆分類(6)

          隨筆檔案(11)

          文章分類(30)

          文章檔案(34)

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 垣曲县| 正阳县| 宜章县| 旌德县| 勐海县| 陈巴尔虎旗| 九江县| 永登县| 彭阳县| 丰镇市| 崇阳县| 宜阳县| 四子王旗| 湟中县| 衡阳县| 梅河口市| 安多县| 卢氏县| 崇信县| 柘城县| 曲周县| 上高县| 刚察县| 开化县| 剑河县| 体育| 翼城县| 台山市| 永兴县| 正蓝旗| 辽宁省| 厦门市| 中方县| 陕西省| 乃东县| 丽江市| 泗水县| 佳木斯市| 邵阳县| 拉孜县| 华宁县|