Last active
August 29, 2015 14:06
-
-
Save fuzhengwei/f7c913e42cfe41977526 to your computer and use it in GitHub Desktop.
java反射基本的方法使用,所有的框架开发都来不开反射技术。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.drdg.test; | |
import java.lang.reflect.Method; | |
public class TestReflect { | |
public static void main(String[] args) throws Exception { | |
System.out.println("获取类下的所有方法:\r\n"); | |
/** | |
* 动态获取TestBean下的get、set方法 | |
*/ | |
Class<?> f = Class.forName("com.drdg.bean.TestBean"); | |
Method[] m = f.getMethods(); | |
for(int i = 0; i < m.length; i ++){ | |
System.out.println(m[i].getName()); | |
} | |
System.out.println("动态调用:\r\n"); | |
/** | |
* 动态调用TestBean下的get、set方法 | |
*/ | |
Object obj = Class.forName("com.drdg.bean.TestBean").newInstance(); | |
Method m_setName = f.getDeclaredMethod(m[1].getName(), String.class); | |
Method m_getName = f.getDeclaredMethod(m[0].getName()); | |
Method m_setNumber = f.getDeclaredMethod(m[3].getName(), String.class); | |
Method m_getNumber = f.getDeclaredMethod(m[2].getName()); | |
m_setName.invoke(obj, "东软帝国"); | |
m_setNumber.invoke(obj, "5307397"); | |
String qqGroupName = (String) m_getName.invoke(obj); | |
String qqGroupNumber = (String) m_getNumber.invoke(obj); | |
System.out.println("群名:"+qqGroupName); | |
System.out.println("群号:"+qqGroupNumber); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
//TestBean.java
package com.drdg.bean;
public class TestBean {
}
/*
运行结果:
获取类下的所有方法:
getQqGroupName
setQqGroupName
getQqGroupNumber
setQqGroupNumber
wait
wait
wait
hashCode
getClass
equals
toString
notify
notifyAll
动态调用:
群名:东软帝国
群号:5307397
*/