久久r热视频,国产午夜精品一区二区三区视频,亚洲精品自拍偷拍,欧美日韩精品二区

您的位置:首頁技術(shù)文章
文章詳情頁

Java如何基于反射獲取對(duì)象屬性信息

瀏覽:3日期:2022-08-22 14:23:17

先建立一個(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)。

標(biāo)簽: Java
相關(guān)文章:
主站蜘蛛池模板: 钟祥市| 乌鲁木齐县| 屯昌县| 师宗县| 毕节市| 丰镇市| 东阿县| 泗水县| 韶关市| 丹寨县| 抚顺县| 滨海县| 小金县| 波密县| 晋城| 金溪县| 清远市| 垦利县| 台南县| 汝南县| 柞水县| 汪清县| 工布江达县| 灌南县| 和静县| 康乐县| 介休市| 成安县| 沁水县| 常州市| 始兴县| 友谊县| 区。| 普格县| 武威市| 积石山| 开远市| 汕尾市| 郓城县| 高要市| 九台市|