javase-reflect-constructor-210709-04
- 反编译一个类的Constructor构造方法
- 通过反射创建对象
- 通过反射获取父类或者获取实现的接口
反编译一个类的Constructor构造方法
ReflectTest01.java
package bgy_reflect_constructor_01;
import java.lang.reflect.Constructor;
import java.lang.reflect.Modifier;
/*
反编译一个类的Constructor构造方法
*/
public class ReflectTest01 {
public static void main(String[] args) throws Exception{
StringBuffer s = new StringBuffer();
Class vipClass = Class.forName("bgy_reflect_constructor_01.Vip");
s.append(Modifier.toString(vipClass.getModifiers()));
s.append(" class ");
s.append(vipClass.getSimpleName());
s.append("{\n");
// 拼接
Constructor[] constructors = vipClass.getConstructors();
for (Constructor constructor : constructors){
s.append("\t");
s.append(Modifier.toString(constructor.getModifiers()));
s.append(" ");
s.append(vipClass.getSimpleName());
s.append(" ");
s.append("(");
// 拼接参数
Class[] parameterTypes = constructor.getParameterTypes();
for (Class parameterType : parameterTypes){
s.append(parameterType.getSimpleName());
s.append(",");
}
// 删除最后位置下标
if (parameterTypes.length > 0){
s.deleteCharAt(s.length()-1);
}
s.append("){}\n");
}
s.append("}");
System.out.println(s);
}
}
通过反射创建对象
ReflectTest02.java
package bgy_reflect_constructor_01;
import java.lang.reflect.Constructor;
/*
通过反射创建对象
*/
public class ReflectTest02 {
public static void main(String[] args) throws Exception{
/*
1.
不通过反射创建对象
*/
Vip v1 = new Vip();
Vip v2 = new Vip(334,"白光一","1999-9-9",true);
/*
2.
使用反射创建对象
*/
// 获取对象
Class vip = Class.forName("bgy_reflect_constructor_01.Vip");
// 01
// 无参构造创建对象
Object obj01 = vip.newInstance();
System.out.println(obj01);
// 02
// 有参构造方法创建对象
// 001. 先获取到这个有参数的构造方法
Constructor constructor = vip.getConstructor(int.class, String.class, String.class, boolean.class);
// 002. 调用有参构造方法new对象
Object obj02 = constructor.newInstance(333, "Jack", "2000-02-02", true);
System.out.println(obj02);
}
}
通过反射获取父类或者获取实现的接口
ReflectTest03.java
package bgy_reflect_constructor_01;
/*
通过反射获取父类或者获取实现的接口
*/
public class ReflectTest03 {
public static void main(String[] args) throws Exception {
Class stringClass = Class.forName("java.lang.String");
// 获取String的父类
Class superclass = stringClass.getSuperclass();
System.out.println(superclass.getName());
// 获取String类实现的所有接口
Class[] interfaces = stringClass.getInterfaces();
for (Class in : interfaces){
System.out.println(in.getName());
}
}
}
Vip.java
package bgy_reflect_constructor_01;
public class Vip {
int no;
String name;
String birth;
boolean sex;
public Vip() {
}
public Vip(int no) {
this.no = no;
}
public Vip(int no, String name) {
this.no = no;
this.name = name;
}
public Vip(int no, String name, String birth) {
this.no = no;
this.name = name;
this.birth = birth;
}
public Vip(int no, String name, String birth, boolean sex) {
this.no = no;
this.name = name;
this.birth = birth;
this.sex = sex;
}
@Override
public String toString() {
return "Vip{" +
"no=" + no +
", name='" + name + '\'' +
", birth='" + birth + '\'' +
", sex=" + sex +
'}';
}
}