Java反射Demo

来源:互联网 发布:淘宝聚划算有什么好处 编辑:程序博客网 时间:2024/05/16 18:04

代码结构:

1、用户Bean类:

package com.wc.plugin;import java.io.Serializable;/** *@function用户Bean类   *@authorWRS *@remark用户Bean类 *@version1.0 *@sincejdk1.8 *@datetime2015年10月4日 下午1:11:21 *@copyright{xx.com (c) 2018} */public class User implements Serializable{private static final long serialVersionUID = 1L;private Long id;private String username;private String userpwd;public User() {super();}public User(Long id, String username, String userpwd) {this.id = id;this.username = username;this.userpwd = userpwd;}public Long getId() {return id;}public void setId(Long id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getUserpwd() {return userpwd;}public void setUserpwd(String userpwd) {this.userpwd = userpwd;}}
2、反射实现Demo:

package com.wc.plugin;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;/** *@function反射Demo *@authorWRS *@remarkJava反射机制 *@version1.0 *@sincejdk1.8 *@datetime2015年10月4日 下午1:10:10 *@copyright{xx.com (c) 2018} */public class ReflectionMain {public static void main(String[] args) throws NumberFormatException {try {Class<?> cls = Class.forName(User.class.getName());User user = (User) cls.newInstance();user.setId(new Long(2015));user.setUsername("JAVA");Method[]  methods = cls.getMethods();//取得User的所有方法for (Method item : methods) {if("getId".equals(item.getName())){Long getId = (Long) item.invoke(user);System.out.println(getId);}else if("getUsername".equals(item.getName())){String getUsername = (String) item.invoke(user);System.out.println(getUsername);}}} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {e.printStackTrace();}    }}

友情提示:本人提供相关IT技术开发和支持,与其相关技术交流。

如需请加微信号:





0 0
原创粉丝点击