Java反射Demo

代码结构:

1、用户Bean类:

package com.wc.plugin;

import java.io.Serializable;

/**
 *	@function	用户Bean类  
 *	@author	WRS
 *	@remark	用户Bean类
 *	@version	1.0
 *	@since	jdk1.8
 *	@datetime	2015年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
 *	@author	WRS
 *	@remark	Java反射机制
 *	@version	1.0
 *	@since	jdk1.8
 *	@datetime	2015年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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值