方法说明:
Class类中有一个方法:
T newInstance() 创建此 Class 对象所表示的类的一个新实例。
前提:
1、反射类必须有空参数构造方法 (因为封装好的newInstance()底层就是调用的空参数构造方法)(以Person类为例)
2、空参数构造方法修饰符不能是private,建议使用public
Class类中的常用方法:(了解)
String getSimpleName() 获取反射类的名字
String getName() 获取反射类的全类名(包名+类名)
举例说明:
package com.ccc.demo02Reflect;
import com.ccc.demo03domain.Person;
public class Demo03Reflect {
public static void main(String[] args) throws Exception {
//1.获取Person类的class文件对象
Class clazz = Class.forName("com.ccc.demo03domain.Person");
//2.使用class文件对象中的方法newInstance实例化对象
Object obj = clazz.newInstance(); //就相当于new Person();
//注:以下的代码是为了展示效果
System.out.println(obj);
Person p = (Person)obj; //目的:使用子类特有成员变量,成员方法
System.out.println(p.getName()+"..."+p.getAge());
System.out.println("===============================");
String simpleName = clazz.getSimpleName();
System.out.println(simpleName); //Person
String name = clazz.getName();
System.out.println(name); //com.ccc.demo03domain.Person
}
}
Person类:
package com.ccc.demo03domain;
public class Person {
private String name;
private int age;
private String sex;
public Person() {
System.out.println("Person类的空参数构造方法");
}
public Person(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
System.out.println("Person类的全参数构造方法");
}
private Person(String name, int age) {
this.name = name;
this.age = age;
System.out.println("Person类的私有构造方法");
}
//私有方法
private void method(){
System.out.println("Person类的私有方法");
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}