请老师检查作业

来源:3-10 自由编程

慕雪6185030

2020-01-17 09:09:59

package com.imooc.reflect.test;


public class Address {

      private int uid;

      private String name;

      private String address;

      private int number;

public Address() {

super();

// TODO Auto-generated constructor stub

}

public Address(int uid, String name, String address, int number) {

super();

this.uid = uid;

this.name = name;

this.address = address;

this.number = number;

}

public int getUid() {

return uid;

}

public void setUid(int uid) {

this.uid = uid;

}

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 int getNumber() {

return number;

}

public void setNumber(int number) {

this.number = number;

}

@Override

public String toString() {

return "Address [uid=" + uid + ", name=" + name + ", address=" + address + ", number=" + number + "]";

}

      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.Constructor;

import java.lang.reflect.Method;


import org.junit.Test;


public class MethodAddress {

         @Test

         //公有方法

         public void demo() throws Exception {

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

             //实例化

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

        //获得公有方法

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

        //执行该方法

        method.invoke(ad);

         }

         @Test

         //私有方法

         public void demo1() throws Exception {

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

             //实例化

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

        //获得私有方法

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

        //设置私有属性的访问权限

        method.setAccessible(true);

        method.invoke(ad, null);

         }

         @Test

         //私有方法带参数

         public void demo2() throws Exception {

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

             //实例化

         

        Constructor c =class1.getDeclaredConstructor(int.class,String.class,String.class,int.class);

        Address ad =(Address) c.newInstance(1,"上海","北京市通州区",12345678);

        //获得私有方法

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

        //设置私有属性的访问权限

        method.setAccessible(true);

        Object obj =method.invoke(ad, "北京");

        System.out.println(obj);

         }

}


写回答

1回答

好帮手慕阿满

2020-01-17

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

祝:学习愉快~

0

0 学习 · 8016 问题

查看课程