先创建一个Joint类,写入showInfo方法:
public class Obj {
private String name;
private String gender;
private Integer age;
public Obj() {
super();
}
public Obj(String name, String gender, Integer age) {
super();
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public void showInfo() {
System.out.println(this.getName()+"---"+this.getGender()+"---"+this.getAge());
}
}
以下是三种方法:
(1)通过属性调取方法实现字符串拼接:
public static void main(String[] args) throws Exception {
Class c=Obj.class;
//此方法为通过属性调取方法
Object o=c.newInstance();
Field jName=c.getDeclaredField("name");//获取属性
Field jSex=c.getDeclaredField("sex");
jName.setAccessible(true);//取消访问修饰符的限制
jName.set(o,"吴亦凡");
jSex.setAccessible(true);
jSex.set(o,"28");
Method show=c.getDeclaredMethod("showInfo");
Object invo=show.invoke(o);
System.out.println(invo);
}
(3)通过构造器:
public static void main(String[] args) throws Exception {
Class c=Obj.class;
Constructor[] cons=c.getDeclaredConstructors();
for(Constructor con:cons){
Class[] paras=con.getParameterTypes();
if(paras.length!=0){
Obj obj=(Obj) con.newInstance(new Object[]{"成龙","男",68});
obj.showInfo();
}
}
}
console:
成龙---男---68