1、 定义封装类Student,类中的成员有:
私有属性:学号,姓名,年龄,性别
无参构造方法,全参数构造方法
定义每个属性的setters 和getters 方法
重写 toString方法和 equals 方法(根据学号比较对象)
在测试类中利用反射完成以下操作:
- 实例化该类,要求调用有参构造方法完成实例化对象的同时为属性赋值
- 获取并遍历类中的所有方法,执行所有的get 开头的方法,并将其返回值打印输出
Student类代码如下:
public class Student {
private String id;
private String name;
private String gender;
private int age;
public Student() {
}
public Student(String id, String name, String gender, int age) {
this.id = id;
this.name = name;
this.gender = gender;
this.age = age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(id, student.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "Student{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", gender='" + gender + '\'' +
", age=" + age +
'}';
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Test代码如下:
public class test1 {
public static void main(String[] args) throws Exception {
// System.out.println("请输入要反射的类");
String className="Student";
Class cls=Class.forName(className);
//通过类名点Class作为参数获取对应的有参构造器,不填默认获取无参构造器
Constructor cons=cls.getConstructor(String.class,String.class,String.class,int.class);
//newInstance通过有参构造器创造对象
Object obj=cons.newInstance("1","张三","男",20);
Student stu1=(Student)obj;
System.out.println(stu1);
Method[] methods=cls.getMethods();
for(Method m:methods){
//获得所有所有Student的getter方法并执行输出get到的值
if(m.getName().contains("get")){
System.out.println("被执行的get方法:"+m.invoke(stu1));
}
}
}
}
2、获取Demo类的私有属性和私有方法,setAccessible设置访问权限为true,可以访问私有方法或属性
public class Test3 {
public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchFieldException {
Class cls=Demo.class;
Method m=cls.getDeclaredMethod("demo");
m.setAccessible(true);
Demo d=(Demo)cls.newInstance();
m.invoke(d);
Field f=cls.getDeclaredField("name");
f.setAccessible(true);
System.out.println(f.get(d));
}
}
class Demo{
private String name="这是私有属性";
private void demo(){
System.out.println("这是私有方法");
}
}