老师检查一下
来源:3-10 自由编程
慕仔0431810
2020-01-03 15:45:29
package com.zt.reflect3;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.junit.Test;
public class Test1 {
@Test
public void test1() throws Exception {
Class class1=Class.forName("com.zt.reflect3.Address");
//实例化
Address add=(Address)class1.newInstance();
//获得公有方法
Method method=class1.getDeclaredMethod("display");
//执行方法
method.invoke(add);
//获得私有方法
Method method2=class1.getDeclaredMethod("info");
//设置访问权限
method2.setAccessible(true);
//执行方法
method2.invoke(add);
Constructor c= class1.getDeclaredConstructor(String.class,String.class,String.class,String.class);
Address add2=(Address)c.newInstance("sss","sss","sss","sss");
//获得有参私有方法
Method method3=class1.getDeclaredMethod("equalsAddress",String.class);
//设置访问权限
method3.setAccessible(true);
//执行方法
method3.invoke(add2,"sss");
}
}package com.zt.reflect3;
public class Address {
private String id;
private String name;
private String despAddress;
private String tel;
public Address() {
}
public Address(String id, String name, String despAddress, String tel) {
super();
this.id = id;
this.name = name;
this.despAddress = despAddress;
this.tel = tel;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDespAddress() {
return despAddress;
}
public void setDespAddress(String despAddress) {
this.despAddress = despAddress;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public void display(){
System.out.println("这是一个地址");
}
private void info(){
System.out.println("我是私有方法");
}
private void equalsAddress(String name){
if(this.name.equals(name)) {
System.out.println("相等");
}else {
System.out.println("不相等");
}
}
@Override
public String toString() {
return "Address [id=" + id + ", name=" + name + ", despAddress=" + despAddress + ", tel=" + tel + "]";
}
}1回答
同学你好。经测试,同学的代码是正确的~
祝学习愉快~
相似问题