浅解反射后的一个小例子

类:
package echo;

public class GetClass {
private String name;
private String age;
private String sex;

public GetClass(){
this.name="zhangsan";
this.age="12";
this.sex="1";
}

public String getPerson(){
String person="";
person=this.getName()+" "+this.getAge()+" "+this.getSex();
return person;
}

public String getNameAndSex(){
String info = "";
info = this.getName()+" "+this.getSex();
return info;
}

public String getNameAndAge(){
String info = "";
info = this.getName()+" "+this.getAge();
return info;
}

public void printSuccessful(){
System.out.println("print successful......!");
}

public void printSuccessful(String str1, String str2){
System.out.println("print2 successful......!");
System.out.println(str1 + "," + str2);
}

public String getAge() {
return age;
}

public void setAge(String age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex;
}


}


测试类:
package test;

import java.lang.reflect.Method;

import junit.framework.TestCase;
import echo.GetClass;

public class Test extends TestCase {

public void testGetClass(){
GetClass gc = new GetClass();
String gClass = "echo.GetClass";
try {
//得到类对象
Class c = Class.forName(gClass);
//得到类实例
Object obj = c.newInstance();

//通过类对象获得类的内部方法
Method m = c.getMethod("printSuccessful",null);
//得到方法对象后用类实例执行方法
m.invoke(obj,null);

//多个参数的写法
m = c.getMethod("printSuccessful",new Class[]{String.class,String.class});
m.invoke(obj,new String[]{"111","222"});

//得到类名包含包在内 例如:echo.GetClass
System.out.println(c.getName());


} catch(Exception e){
System.out.println(e.toString());
}
}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值