Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
-
method
(1), Class.forname ( "full class name"); the bytecode file loaded into memory, return Class
used for the configuration file, the class name is defined in the configuration file, read the file, the class is loaded
(2), class name .class: property class obtained by class name
used for the transmission parameters
(3), the object .getClass (); getClass () method is defined in the object class
bytecode files used for acquiring the object -
Case
1, the establishment of a demain package, inside the definition of a Person class
package domain;
public class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public Person() {
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
2, the definition of a class ReflectDemo1
package indi.zxp.reflect;
import domain.Person;
public class ReflectDemo1 {
/**
* 1,Class.forName("全类名");将字节码文件加载进内存,返回Class
* 多用于配置文件,将类名定义在配置文件中,读取文件,加载类
* 2,类名.class:通过类名的属性class获取
* 多用于参数的传递
* 3,对象.getClass();getClass()方法在object类中定义
* 多用于获取对象的字节码文件
* @param args
*/
public static void main(String[] args) throws Exception{
//1.Class.forName("全类名");
Class cls1 = Class.forName("domain.Person");
System.out.println(cls1);
//2.类名.class
Class cls2 = Person.class;
System.out.println(cls2);
//3.对象.getClass()
Person person = new Person();
Class cls3 = person.getClass();
System.out.println(cls3);
//用 == 比较三个对象
System.out.println(cls1 == cls2);
System.out.println(cls1 == cls3);
}
}
3. Results