获取字节码对象
1)Class.forName("类的全路径");
2)类名.class
3)new 对象.getClass
反射
反射的前提:我们要获取、使用别人代码的功能
代码必须获取字节码对象(3种方式),才能进一步操作
单元测试方法
@Test+void+没有参数+public1
package cn.tedu.reflection;
/*反射测试的物流类,假装不是自己写的 别人写的*/
public class Student {
String name;
int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public void eat(){
System.out.println("普通方法吃"+name);
}
}
package cn.tedu.reflection;
import org.junit.Test;
public class TestReflect {
/*单元测试方法:java运行测试的最小单位,使用灵活,推荐程度5
* 语法要求:@Test+void+没有参数+public
* */
@Test
public void getClazz() throws ClassNotFoundException {
Class<?> student1 = Class.forName("cn.tedu.reflection.Student");
Class<Student> student2 = Student.class;
Class<? extends Student> student3 = new Student().getClass();
System.out.println(student1);//字节码对象
System.out.println(student2.getName());//获取类的全路径名
System.out.println(student3.getSimpleName());//
}
}
package cn.tedu.reflection;
import org.junit.Test;
import java.awt.event.FocusEvent;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
public class TestReflection1 {
@Test
public void getConstrct(){
Class<?> clazz=Student.class;
//获取构造方法
Constructor<?>[] constructors = clazz.getConstructors();
for ( Constructor<?> df:constructors
) {
System.out.println(df);
String name = df.getName();//构造方法名
Class<?>[] parameterTypes = df.getParameterTypes();//构造方法类型—(数组打印)
}
}
//获取Student普通方法
@Test
public void getfuntion(){
Class<Student> clazz = Student.class;
Method[] methods = clazz.getMethods();
for (Method tt:methods
) {
// System.out.println(tt);
String name = clazz.getName();
Class<?>[] parameterTypes = tt.getParameterTypes();
}
}
//获取所有成员变量
@Test
public void getFields(){
Class<Student> clazz = Student.class;
Field[] fs = clazz.getFields();
for (Field tt:fs
) {
System.out.println(tt.getName());//成员变量名
System.out.println(tt.getType().getName());//类型
}
}
//创建对象
@Test
public void getObject() throws IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException {
Class<Student> clazz = Student.class;
//无参构造快捷
Student student = clazz.newInstance();
System.out.println(student);
//创建含参数的对象,传入的字节码对象
Constructor<Student> constructor = clazz.getConstructor(String.class, int.class);
Student haimian = constructor.newInstance("海绵韩云", 3);
String name = haimian.name;
System.out.println(name);
haimian.eat(66);
}
}
|