国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術文章
文章詳情頁

Java如何基于反射獲取對象屬性信息

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

先建立一個類,有四種屬性:

private int id; private String name; private byte by; private short st;

以下方法,創建一個對象,然后打印該對象的屬性名字,屬性值,和屬性的類型:

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);}/** * 獲得一個對象各個屬性的字節流 */@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);}}

打印結果如下:

id 1 int name cc class java.lang.String by 1 byte st 2 short

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。

標簽: Java
相關文章:
主站蜘蛛池模板: 九寨沟县| 乌拉特后旗| 南川市| 岑巩县| 奈曼旗| 蚌埠市| 深泽县| 会昌县| 扎兰屯市| 分宜县| 广南县| 贵溪市| 定结县| 五峰| 江孜县| 大丰市| 通海县| 东城区| 齐河县| 唐海县| 瑞安市| 富锦市| 江津市| 天台县| 长阳| 广宁县| 邵阳县| 法库县| 中宁县| 黄浦区| 渝中区| 武夷山市| 东安县| 连平县| 小金县| 灵石县| 赤水市| 若尔盖县| 苍梧县| 中宁县| 天镇县|