老师,demo3这个方法哪里错了?
来源:3-10 自由编程
一心励志当码农
2019-11-12 22:29:23
package com.imooc.reflect;
public class Address {
private String id;
private String name;
private String add;
private String telephone;
public Address() {
super();
// TODO Auto-generated constructor stub
}
public Address(String id, String name, String add, String telephone) {
super();
this.id = id;
this.name = name;
this.add = add;
this.telephone = telephone;
}
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 getAdd() {
return add;
}
public void setAdd(String add) {
this.add = add;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
@Override
public String toString() {
return "Address [id=" + id + ", name=" + name + ", add=" + add + ", telephone=" + telephone + "]";
}
public void display() {
System.out.println("这是一个地址");
}
private void info(){
System.out.println("我是私有方法");
}
private void equalsAddress(String name){
if(name.equals(this.name)) {
System.out.println("相等");
}else {
System.out.println("不相等");
}
}
}package com.imooc.reflect;
import java.lang.reflect.Method;
import org.junit.Test;
public class AddressTest {
@Test
public void demo1() throws Exception {
Class class1 = Class.forName("com.imooc.reflect.Address");
Address add = (Address) class1.newInstance();
Method method = class1.getMethod("display");
method.invoke(add);
}
@Test
public void demo2() throws Exception {
Class class1 = Class.forName("com.imooc.reflect.Address");
Address add = (Address) class1.newInstance();
Method method = class1.getDeclaredMethod("info");
method.setAccessible(true);
method.invoke(add);
}
public void demo3() throws Exception {
Class class1 = Class.forName("com.imooc.reflect.Address");
Address add = (Address) class1.newInstance();
Method method = class1.getDeclaredMethod("equalsAddress", String.class);
method.setAccessible(true);
Address add1 = new Address();
add1.setAdd("Beijing");
method.invoke(add, "Beijing");
}
}1回答
同学你好。首先是要在demo3上使用@Test注解才能测试到呢~同学的测试结果为“不相等”,是因为同学使用的不是同一个Address对象。equalsAddress
方法需要使用当前对象的name属性和传入的参数做比较,因此需要使用同一个Address对象哦~以下运行结果为“相等”:
@Test
public void demo3() throws Exception {
Class class1 = Class.forName("com.imooc.reflect.Address");
Address add = (Address) class1.newInstance();
Method method = class1.getDeclaredMethod("equalsAddress", String.class);
method.setAccessible(true);
add.setName("Beijing");
method.invoke(add, "Beijing");
}如果解答了同学的疑问,望采纳~
祝学习愉快~
相似问题