您的位置:首页 > 编程语言 > Java开发

Java反射Demo

2015-10-21 15:24 465 查看
代码结构:



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技术开发和支持,与其相关技术交流。

如需请加微信号:
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息