交作业交作业交作业
来源:3-10 自由编程
mixiaofan
2019-10-10 12:05:20
package com.imooc.reflecttest.work;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import org.junit.Test;
public class Demo3 {
@Test
/**
* 1)公有通过Method调用display()方法
*/
public void demo1() throws Exception {
Class class1 = Class.forName("com.imooc.reflecttest.work.Address");
Address ad1 = (Address) class1.newInstance();
Method me1 = class1.getMethod("display");
me1.invoke(ad1);
}
@Test
/**
* 2)私有通过Method调用info()方法
*/
public void demo2() throws Exception {
Class class1 = Class.forName("com.imooc.reflecttest.work.Address");
Address ad1 = (Address) class1.newInstance();
Method me1 = class1.getDeclaredMethod("info");
me1.setAccessible(true);
me1.invoke(ad1);
}
@Test
/**
* 3)私有通过Method调用equalsAddress()方法
*/
public void demo3() throws Exception {
Class class1 = Class.forName("com.imooc.reflecttest.work.Address");
Address ad1 = (Address) class1.newInstance();
Field field = class1.getDeclaredField("name");
field.setAccessible(true);
field.set(ad1, "eee1");
Method me1 = class1.getDeclaredMethod("equalsAddress", String.class);
me1.setAccessible(true);
Object obj = me1.invoke(ad1, "eee");
System.out.println(obj);
}
}package com.imooc.reflecttest.work;
public class Address {
private int adid;
private String name;
private String adr;
private int tel;
public Address() {
super();
}
public Address(int adid, String name, String adr, int tel) {
super();
this.adid = adid;
this.name = name;
this.adr = adr;
this.tel = tel;
}
public int getAdid() {
return adid;
}
public void setAdid(int adid) {
this.adid = adid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAdr() {
return adr;
}
public void setAdr(String adr) {
this.adr = adr;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
@Override
public String toString() {
return "Address [adid=" + adid + ", name=" + name + ", adr=" + adr + ", tel=" + tel + "]";
}
public void display() {
System.out.println("这是一个地址");
}
private void info() {
System.out.println("我是私有方法");
}
private String equalsAddress(String name) {
String str = null;
if (this.getName().equals(name)) {
str = "相等";
} else {
str = "不相等";
}
return str;
}
}1回答
芝芝兰兰
2019-10-10
同学你好。经测试,同学的代码是正确的~
棒棒的~再接再厉哦~
祝学习愉快~