请老师看一下
来源:3-10 自由编程
96年的nash
2019-05-16 12:10:19
package com.hxh.reflect.practise;
public class Address {
private Long addressId;
private String name;
private String address;
private Long phone;
public Address() {
}
public Address(Long addressId, String name, String address, Long phone) {
this.addressId = addressId;
this.name = name;
this.address = address;
this.phone = phone;
}
public Long getAddressId() {
return addressId;
}
public void setAddressId(Long addressId) {
this.addressId = addressId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Address{" +
"addressId=" + addressId +
", name='" + name + '\'' +
", address='" + address + '\'' +
", phone=" + phone +
'}';
}
public void display(){
System.out.println(toString());
}
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.hxh.reflect.practise;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import org.junit.Test;
public class MethodTest {
@Test
public void testMethod() throws Exception{
Class class1 = Class.forName("com.hxh.reflect.practise.Address");
Constructor constructor = class1.getConstructor(Long.class,String.class,String.class,Long.class);
Address address = (Address) constructor.newInstance(272600l,"张楠","北京师范大学",119l);
//System.out.println(address);
//通过Method调用display()方法
Method method1 = class1.getMethod("display");
method1.invoke(address);
//通过Method调用info()方法
Method method2 = class1.getDeclaredMethod("info");
method2.setAccessible(true);
method2.invoke(address);
//通过Method调用equalsAddress()方法
Method method3 = class1.getDeclaredMethod("equalsAddress", String.class);
method3.setAccessible(true);
method3.invoke(address, "李若彤");
Method method4 = class1.getDeclaredMethod("equalsAddress", String.class);
method4.setAccessible(true);
method4.invoke(address, "张楠");
}
}1回答
同学你好,写的很棒~
继续加油吧~祝:学习愉快~
相似问题