3-10 自由编程

来源:3-10 自由编程

csm032

2020-04-26 21:34:13

package com.imooc.reflect.test;

public class Address {
	private int id;
	private String name;
	private String addr;
	private String tel;

	public Address() {
		super();
		// TODO Auto-generated constructor stub
	}

	public Address(int id, String name, String addr, String tel) {
		super();
		this.id = id;
		this.name = name;
		this.addr = addr;
		this.tel = tel;
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAddr() {
		return addr;
	}

	public void setAddr(String addr) {
		this.addr = addr;
	}

	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.getAddr().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 {
	//display()方法
	@Test
	public void demo1() throws Exception {
		Class class1=Class.forName("com.imooc.reflect.test.Address");
		Address addr=(Address) class1.newInstance();
		Method m=class1.getMethod("display");
		m.invoke(addr, null);
	}
	
	//调用info()方法
	@Test
	public void demo2() throws Exception {
		Class class1=Class.forName("com.imooc.reflect.test.Address");
		Address addr=(Address) class1.newInstance();
		Method m=class1.getDeclaredMethod("info");
		m.setAccessible(true);
		m.invoke(addr, null);
	}	
	
	//调用equalsAddress()方法
	@Test
	public void demo3() throws Exception {
		Class class1=Class.forName("com.imooc.reflect.test.Address");
		Address addr=(Address) class1.newInstance();
		//field
		Field field=class1.getDeclaredField("addr");		
		field.setAccessible(true);
		field.set(addr, "武汉");
		Object obj=field.get(addr);
		System.out.println(obj);
		//method
		Method method=class1.getDeclaredMethod("equalsAddress", String.class);
		method.setAccessible(true);
		method.invoke(addr, "武汉");
		method.invoke(addr, "北京");
		
		
	}



}


写回答

1回答

好帮手慕小脸

2020-04-27

同学的代码完成的不错,继续加油。

祝:学习愉快~


0

0 学习 · 8016 问题

查看课程

相似问题