Java如何基于反射獲取對象屬性信息
先建立一個類,有四種屬性:
private int id; private String name; private byte by; private short st;
以下方法,創(chuàng)建一個對象,然后打印該對象的屬性名字,屬性值,和屬性的類型:
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);}/** * 獲得一個對象各個屬性的字節(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());}}/** * 獲得對象屬性的值 */@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)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. 將properties文件的配置設(shè)置為整個Web應(yīng)用的全局變量實現(xiàn)方法2. SpringBoot集成SSM、Dubbo、Redis、JSP的案例小結(jié)及思路講解3. python爬蟲利用代理池更換IP的方法步驟4. JavaScript forEach中return失效問題解決方案5. JS算法題解旋轉(zhuǎn)數(shù)組方法示例6. PHP設(shè)計模式之迭代器模式Iterator實例分析【對象行為型】7. VMware如何進(jìn)入BIOS方法8. python中pandas.read_csv()函數(shù)的深入講解9. Python語言規(guī)范之Pylint的詳細(xì)用法10. springboot用controller跳轉(zhuǎn)html頁面的實現(xiàn)
