[Java] 反射 Java使用反射访问类中的方法 →→→→→进入此内容的聊天室

来自 , 2019-12-17, 写在 Java, 查看 104 次.
URL http://www.code666.cn/view/7fec306d
  1. package com.jiangqq.reflection;  
  2. import java.lang.reflect.Constructor;  
  3. import java.lang.reflect.Method;  
  4. /**
  5.  * 反射练习二,使用反射访问类中的方法
  6.  *  
  7.  * @author jiangqq
  8.  *  
  9.  */  
  10. public class Reflection2 {  
  11.     public int sum(int a, int b) {  
  12.         return a + b;  
  13.     }  
  14.     public String addStr(String str) {  
  15.         return "This is the:" + str;  
  16.     }  
  17.     public static void main(String[] args) throws Exception {  
  18.         Class<?> classType = Reflection2.class;  
  19.         // Object reflection2 = classType.newInstance();  
  20.         Constructor<?> constructor = classType.getConstructor(new Class[] {});  
  21.         Object reflection2 = constructor.newInstance(new Object[] {});  
  22.         // 通过反射进行反射出类中的方法  
  23.         Method sumMethod = classType.getMethod("sum", new Class[] { int.class,  
  24.                 int.class });  
  25.         //invoke方法的值永远只是对象  
  26.         Object result1 = sumMethod.invoke(reflection2, new Object[] { 6, 10 });  
  27.         System.out.println((Integer) result1);  
  28.         Method addStrMethod = classType.getMethod("addStr",  
  29.                 new Class[] { String.class });  
  30.         Object result2 = addStrMethod.invoke(reflection2,  
  31.                 new Object[] { "tom" });  
  32.         System.out.println((String) result2);  
  33.     }  
  34. }  
  35.  
  36. //源代码片段来自云代码http://yuncode.net
  37.                        

回复 "反射 Java使用反射访问类中的方法"

这儿你可以回复上面这条便签

captcha