java类反射获取类对象的三种方法
//获取class对象的三种方法
public class ReflectDemo1 {
public static void main(String[] args) throws ClassNotFoundException {
//1.通过class属性获取
Class<Student> studentClass1 = Student.class;
System.out.println(studentClass1);
//2.通过对象的getClass方法获取
Student student = new Student();
Class<? extends Student> studentClass2 = student.getClass();
//因为class对象为同一个所以可以通过==判断对象是否为同一个
System.out.println(studentClass1 == studentClass2);
//3.通过Class类的静态方法forName获取class对象
Class<?> aClass = Class.forName("mystring.demo4.Student");
System.out.println(aClass == studentClass1);
}
}
Student类后续都要用到,反射的模板
package mystring.demo4;
public class Student {
//成员变量:一个私有,一个默认,一个公共
private String name;
int age;
public String address;
//构造方法:一个私有,一个默认,两个公共
public Student() {
}
private Student(String name) {
this.name = name;
}
Student(String name, int age) {
this.name = name;
this.age = age;
}
public Student(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
//成员方法:一个私有,四个公共
private void function() {
System.out.println("function");
}
public void method1() {
System.out.println("method");
}
public void method2(String s) {
System.out.println("method:" + s);
}
public String method3(String s, int i) {
return s + "," + i;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", address='" + address + '\'' +
'}';
}
void say(){
System.out.println("I love code");
}
}