代码结构:
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技术开发和支持,与其相关技术交流。
如需请加微信号: