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

          2.獲取某個類或某個對象所對應的Class對象常用的3種方式
          a)使用Class類的靜態方法forName:Class.forName("java.lang.String")
          b)使用類語法String.class
          c)使用對象的getClass()方法:String s ="aa";
          Class<?> clazz= s.getClass(); 
            不帶參數的構造方法,生成對象
           a)先獲得Class對象,然后通過Class對象newInstance() 方法直接生成對象。
           b) 先獲得Class對象,然后通過該對象獲得對應的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 相關

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

          常用鏈接

          留言簿(1)

          隨筆分類(6)

          隨筆檔案(11)

          文章分類(30)

          文章檔案(34)

          搜索

          •  

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 嵩明县| 怀安县| 建湖县| 磐石市| 探索| 乌审旗| 甘南县| 建瓯市| 泗洪县| 望奎县| 育儿| 甘洛县| 毕节市| 莱西市| 凉山| 临桂县| 舒兰市| 白水县| 南召县| 杂多县| 宣恩县| 安义县| 金昌市| 宜昌市| 鹤庆县| 台东县| 北票市| 邓州市| 华亭县| 辛集市| 抚松县| 万安县| 镇江市| 启东市| 阿巴嘎旗| 临汾市| 右玉县| 合作市| 大英县| 彭泽县| 抚宁县|