Java如何基于反射獲取對(duì)象屬性信息
先建立一個(gè)類,有四種屬性:
private int id; private String name; private byte by; private short st;
以下方法,創(chuàng)建一個(gè)對(duì)象,然后打印該對(duì)象的屬性名字,屬性值,和屬性的類型:
public class T {public static void main(String[] args) throws Exception {User u = new User();u.setId(1);u.setName('cc');u.setBy((byte)1);u.setSt((short)2);getProperty(u);}/** * 獲得一個(gè)對(duì)象各個(gè)屬性的字節(jié)流 */@SuppressWarnings('unchecked')public static void getProperty(Object entityName) throws Exception {Class c = entityName.getClass();Field field[] = c.getDeclaredFields();for (Field f : field) {Object v = invokeMethod(entityName, f.getName(), null);System.out.println(f.getName() + 't' + v + 't' + f.getType());}}/** * 獲得對(duì)象屬性的值 */@SuppressWarnings('unchecked')private static Object invokeMethod(Object owner, String methodName,Object[] args) throws Exception {Class ownerClass = owner.getClass();methodName = methodName.substring(0, 1).toUpperCase()+ methodName.substring(1);Method method = null;try {method = ownerClass.getMethod('get' + methodName);} catch (SecurityException e) {} catch (NoSuchMethodException e) {return ' can’t find ’get' + methodName + '’ method';}return method.invoke(owner);}}
打印結(jié)果如下:
id 1 int name cc class java.lang.String by 1 byte st 2 short
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. JSP+Servlet實(shí)現(xiàn)文件上傳到服務(wù)器功能2. CSS可以做的幾個(gè)令你嘆為觀止的實(shí)例分享3. 概述IE和SQL2k開發(fā)一個(gè)XML聊天程序4. jsp實(shí)現(xiàn)textarea中的文字保存換行空格存到數(shù)據(jù)庫的方法5. javascript xml xsl取值及數(shù)據(jù)修改第1/2頁6. 低版本IE正常運(yùn)行HTML5+CSS3網(wǎng)站的3種解決方案7. 讀大數(shù)據(jù)量的XML文件的讀取問題8. jsp文件下載功能實(shí)現(xiàn)代碼9. JSP之表單提交get和post的區(qū)別詳解及實(shí)例10. jsp+servlet實(shí)現(xiàn)猜數(shù)字游戲
