package com.gillion.javaReflection;
import java.awt.Button; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Hashtable; /** * @Description Java的反射机制 * @author [email protected] * @time 2015年1月8日 下午4:53:24 * @version 1.0.0 */ public class ReflectionTest { /** * 入口 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { ReflectionTest reflection = new ReflectionTest(); reflection.getNameTest(); System.out.println(""); reflection.getMethodTest(); } /** * 获取类名 全路径 * @throws Exception */ public void getNameTest() throws Exception { System.out.println("===========begin getNameTest============"); String name = "阿蜜果"; Class cls = name.getClass(); System.out.println("String类名: " + cls.getName()); Button btn = new Button(); Class btnClass = btn.getClass(); System.out.println("Button类名: " + btnClass.getName()); Class superBtnClass = btnClass.getSuperclass(); System.out.println("Button的父类名: " + superBtnClass.getName()); Class clsTest = Class.forName("java.awt.Button"); System.out.println("clsTest name: " + clsTest.getName()); System.out.println("===========end getNameTest============"); } public void getMethodTest() throws Exception { System.out.println("===========begin getMethodTest=========="); Class cls = Class.forName("com.gillion.javaReflection.ReflectionTest"); Class ptypes[] = new Class[2]; ptypes[0] = Class.forName("java.lang.String"); ptypes[1] = Class.forName("java.util.Hashtable"); //参数调用 Method method = cls.getMethod("testMethod", ptypes); /*** * 需要注入哪些参数,参数类型是什么,有多少个参数 */ Method []m= cls.getMethods(); if(m!=null &&m.length>0) { for (int i = 0; i < m.length; i++) { if(m[i].getName().equals("testMethod")){ Parameter []p=m[i].getParameters(); if(p!=null && p.length>0) { for (Parameter parameter : p) { System.out.println(parameter.getType().getName()); } } } } } Object args[] = new Object[2]; args[0] = "hello, my dear!"; Hashtable<String, String> ht = new Hashtable<String, String>(); ht.put("name", "阿蜜果"); args[1] = ht; String returnStr = (String) method.invoke(new ReflectionTest(), args); System.out.println("returnStr= " + returnStr); System.out.println("===========end getMethodTest=========="); } public String testMethod(String str, Hashtable ht) throws Exception { String returnStr = "返回值"; System.out.println("测试testMethod()方法调用"); System.out.println("str= " + str); System.out.println("名字= " + (String) ht.get("name")); System.out.println("结束testMethod()方法调用"); return returnStr; } } |