3-10 自由编程

来源:3-10 自由编程

慕的地2082093

2020-03-14 16:24:52

package com.imooc.reflect.test;


public class Address {

private String addId;

private String name;

private String despAdd;

private String telep;

public Address() {

super();

// TODO Auto-generated constructor stub

}

public Address(String addId, String name, String despAdd, String telep) {

super();

this.addId = addId;

this.name = name;

this.despAdd = despAdd;

this.telep = telep;

}

public String getAddId() {

return addId;

}

public void setAddId(String addId) {

this.addId = addId;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public String getDespAdd() {

return despAdd;

}

public void setDespAdd(String despAdd) {

this.despAdd = despAdd;

}

public String getTelep() {

return telep;

}

public void setTelep(String telep) {

this.telep = telep;

}

@Override

public String toString() {

return "Address [addId=" + addId + ", name=" + name + ", despAdd=" + despAdd + ", telep=" + telep + "]";

}

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("不相等");

}

}

package com.imooc.reflect.test;


import java.lang.reflect.Field;

import java.lang.reflect.Method;


import org.junit.Test;


public class MethodTest {

@Test

/**

* 测试公有方法

* @throws Exception

*/

public void demo() throws Exception {

Class class1 = Class.forName("com.imooc.reflect.test.Address");

Address a = (Address)class1.newInstance();

Method method = class1.getMethod("display");

method.invoke(a);

}

@Test

/**

* 测试私有方法

* @throws Exception

*/

public void demo2() throws Exception {

Class class1 = Class.forName("com.imooc.reflect.test.Address");

Address a = (Address)class1.newInstance();

Method method = class1.getDeclaredMethod("info");

method.setAccessible(true);

method.invoke(a);

}

@Test

/**

*测试私有方法带参数

* @throws Exception

*/

public void demo3() throws Exception {

Class class1 = Class.forName("com.imooc.reflect.test.Address");

Address a = (Address)class1.newInstance();

Field field = class1.getDeclaredField("name");

field.setAccessible(true);

field.set(a, "北京");

Method method = class1.getDeclaredMethod("equalsAddress", String.class);

method.setAccessible(true);

method.invoke(a, "北京");

}

}


写回答

1回答

好帮手慕阿莹

2020-03-14

同学的代码写的不错哦,继续加油哦!!

符合作业要求。

如果我的回答解决了你的问题,请采纳,祝学习愉快.

0

0 学习 · 8016 问题

查看课程

相似问题