## 反射具体实现
package reflect;
import java.lang.reflect.Method;
public class Tests {
public static void main(String[] args) throws Exception{
//refeltEntity().show("welcome");;//entity.show("welcome");
refeltMethod();
}
/**
* 通过反射获取java类中get方法对应的值
* @throws Exception
* @Description:
*/
public static void getValueEnter() throws Exception{
//String from, String to, String position, int id
IpBean entity = new IpBean("北京","上海","9.11116",101);
Class clz = entity.getClass();
Method[] methods = clz.getDeclaredMethods();
String methodName = "";
String methodVal = "";
for(Method m:methods){
methodName = m.getName();
//System.out.println(methodName.indexOf("get"));
if(methodName.indexOf("get")==0){
Object obj = m.invoke(entity,null);
methodVal = obj==null?"":obj.toString();
System.out.println(methodName+":"+methodVal);
}
}
}
public static void refeltMethod() throws Exception{
String IpCls = "reflect.IpBean";
Class clz = Class.forName(IpCls);
//获取类的完整路径
System.out.println(clz.getName());
IpBean entity = (IpBean) clz.newInstance();
entity.setFrom("beijing");
entity.setTo("xianguang");
/**
* 第一个参数是函数的名称,第二个参数是...(表示有无限个参数)表示函数的参数
*/
Method method = clz.getMethod("show", String.class);
/**
* 第一个参数是调用函数的对象,第二个参数是函数执行时的参数
* entity.show("welcome");
*/
method.invoke(entity, "welcome");
/**
* 同样可以调用静态方法
*/
method = clz.getMethod("getMsg", String.class,String.class);
method.invoke(clz, "张斌",22+"");
}
public static IpBean refeltEntity() throws Exception{
String IpCls = "reflect.IpBean";
Class clz = Class.forName(IpCls);
//获取类的完整路径
System.out.println(clz.getName());
IpBean entity = (IpBean) clz.newInstance();
entity.setFrom("beijing");
entity.setTo("xianguang");
return entity;
}
}
## 新建一个实体类
package reflect;
public class IpBean {
private String from; // IP段起始
private String to; // IP结束
private String position; // 地理名称
private int id = 0;
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTo() {
return to;
}
public void setTo(String to) {
this.to = to;
}
public String getPosition() {
return position;
}
public void setPosition(String position) {
this.position = position;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public void show(String msg) {
System.out.println(from + "---" + to + "-->" + msg);
}
public static void getMsg(String name, String age) {
System.out.println(name + "----->" + age);
}
}