文章目录
一、反射是什么?
反射机制允许程序在执行期间借助Reflection取得任何类的内部信息,并能直接操作任意对象的内部属性以及方法。
正常方式:引入包——》通过new——》取得实例化对象
反射机制:实例化对象——》getclass()——》得到包
二、反射内容
1.通过反射获得对象
代码如下(示例):
package reflection;
public class test3 {
public static void main(String[] args) throws ClassNotFoundException {
//通过反射获得class对象
Class aClass = Class.forName("reflection.User");
System.out.println(aClass);
//一个类在内存中只有一个class对象
//一个类被加载后,整个结构都会封装在class对象中
Class c1 = Class.forName("reflection.User");
Class c2 = Class.forName("reflection.User");
Class c3= Class.forName("reflection.User");
System.out.println(c1.hashCode()+"||"+c2.hashCode()+"||"+c3.hashCode());
}
}
class User{
private String name;
private int id;
private int age;
public User() {
}
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
2.不同的class对象
package reflection;
import java.lang.annotation.ElementType;
public class test04 {
public static void main(String[] args) {
Class c1=Object.class;
Class c2=Comparable.class;
Class c3=String[].class;
Class c4=int[][].class;
Class c5=Override.class;
Class c6= ElementType.class;
Class c7=Integer.class;
Class c8=void.class;
Class c9=Class.class;
System.out.println(c1);
System.out.println(c2);
System.out.println(c3);
System.out.println(c4);
System.out.println(c5);
System.out.println(c6);
System.out.println(c7);
System.out.println(c8);
System.out.println(c9);
}
}
2.类的加载:
过程: 加载——》链接——》初始化
加载:将class文件字节码内容加载到内存中,将这些静态数据转换成方法区的运行时数据,然后生成一个代表这个类的java.lang.Class对象。
链接:将java类的二进制加入jvm的运行状态之中的过程:
- 验证:确保加载类信息符合规范,没有安全问题
- 准备:分配内存并初始化
- 解析:虚拟机的符号引用替换为直接引用。
初始化:执行构造器<clinit>()方法的过程。
package reflection;
public class test06 {
static {
System.out.println("main方法加载");
}
public static void main(String[] args) throws ClassNotFoundException {
//主动引用
Son son=new Son();
//class加载(反射产生主动引用)
// Class.forName("reflection.Son");
//不会产生类的引用的方法
System.out.println(Son.b);
Son[] array=new Son[5];
}
}
class Father{
static int c=2;
static {
System.out.println("父类被加载");
}
}
class Son extends Father{
static {
System.out.println("子类被加载");
a=300;
}
static int a=100;
static final int b=1;
}
2.类加载器:
作用:生成一个代表这个类的java.lang.Class对象
类缓存:类加载器可以按要求查找,如何某个类被加载到类加载器中,这个类会缓存一段时间,然后通过jvm垃圾回收机制进行回收。
jvm定义的加载器类型:
- 引导类加载器:负责java平台核心库
- 扩展类加载器:负责jre、lib、ext目录
- 系统类加载器:负责java-classpath
package reflection;
public class test07 {
public static void main(String[] args) throws ClassNotFoundException {
//获取系统类的加载器
ClassLoader systemClassLoader = ClassLoader.getSystemClassLoader();
System.out.println(systemClassLoader);
//获取系统类加载器的父类加载器(扩展类加载器)
ClassLoader parent = systemClassLoader.getParent();
System.out.println(parent);
//获得扩展类加载器的父类加载器(根加载器)
ClassLoader parent1 = parent.getParent();
System.out.println(parent1);
//测试当前类是哪个加载器加载的
ClassLoader classLoader = Class.forName("reflection.test07").getClassLoader();
System.out.println(classLoader);
//获得系统类加载器可以加载的路径
System.out.println(System.getProperty("java.class.path"));
}
}
3.获得类中的属性,方法等
User类:
class User{
private String name;
private int id;
private int age;
public User() {
}
public User(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
import java.lang.reflect.Method;
public class test08 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException {
Class aClass = Class.forName("reflection.test3.User");
//获得类的名字
System.out.println(aClass.getName()); //包名+类名
System.out.println(aClass.getSimpleName()); //类名
//getFields可以找到public属性
//获得类的属性
Field[] fields = aClass.getDeclaredFields();
for (Field f :
fields) {
System.out.println(f);
}
//获得指定属性的值
Field name = aClass.getDeclaredField("name");
System.out.println(name);
//获得类的方法
aClass.getMethods(); //获得本类和父类public的
aClass.getDeclaredMethods();// 获得本类的所有方法
//获得类的指定方法
Method getName = aClass.getMethod("getName", null);
Method setName = aClass.getMethod("setName", String.class);
System.out.println(getName);
System.out.println(setName);
//获得指定的构造器
Constructor[] constructors = aClass.getConstructors(); //public
Constructor[] declaredConstructors = aClass.getDeclaredConstructors(); //所有
for (Constructor constructor:constructors){
System.out.println(constructor);
}
for (Constructor declaredConstructor:declaredConstructors){
System.out.println(declaredConstructor);
}
//获得指定构造器
Constructor constructor = aClass.getConstructor(String.class, Integer.class, Integer.class);
System.out.println(constructor);
}
}
3.动态创建对象执行方法
package reflection;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class test09 {
public static void main(String[] args) throws Exception {
Class aClass = Class.forName("reflection.test3.User");
User user= (User) aClass.newInstance();//必须User中有无参构造
Constructor constructor = aClass.getDeclaredConstructor(String.class, Integer.class, Integer.class);
User user1= (User) constructor.newInstance("zyf",10,20);
System.out.println(user1);
//通过反射调用方法1.通过反射获得方法
Method setName = aClass.getDeclaredMethod("setName", String.class);
//invoke :激活(对象,值)
setName.invoke(user,"zyf");
System.out.println(user);
//通过反射操作属性
Field name = aClass.getDeclaredField("name");
//不能直接操作私有属性,要关闭安全检测:name.setAccessible(true);
name.setAccessible(true);
//set传值
name.set(user,"zyf");
System.out.println(name);
}
3.反射调用与普通调用的性能分析
正常方式>反射方式(关闭检测)>反射方式
4.获得泛型
package reflection;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
public class test10 {
public void test1(Map<String,User> map, List<User> list){
System.out.println("01方法");
}
public Map<String,User> test2(){
System.out.println("02方法");
return null;
}
public static void main(String[] args) throws NoSuchMethodException {
Method method = test10.class.getMethod("test1", Map.class, List.class);
Type[] types = method.getGenericParameterTypes();
for (Type type:types){
System.out.println(type);
if (type instanceof ParameterizedType){
Type[] arguments = ((ParameterizedType) type).getActualTypeArguments();
for (Type argument : arguments) {
System.out.println(argument);
}
}
}
method = test10.class.getMethod("test2", null);
Type type = method.getGenericReturnType();
if (type instanceof ParameterizedType){
Type[] arguments = ((ParameterizedType) type).getActualTypeArguments();
for (Type argument : arguments) {
System.out.println(argument);
}
}
}
}
5.获得注解信息
orm: Object Relationship Mapping
package reflection;
import java.lang.annotation.*;
import java.lang.reflect.Field;
public class test11 {
public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException {
Class<?> aClass = Class.forName("reflection.UserInfo");
Annotation[] annotations = aClass.getAnnotations();
//获得注解
for (Annotation annotation : annotations) {
System.out.println(annotation);
}
//获得注解的值
TableC annotation = aClass.getAnnotation(TableC.class);
System.out.println(annotation.value());
//获得类指定的注解
Field name = aClass.getDeclaredField("name");
FieldC c = name.getAnnotation(FieldC.class);
System.out.println(c.columnName());
System.out.println(c.type());
System.out.println(c.length());
}
}
@TableC("db_userInfo")
class UserInfo{
@FieldC(columnName = "db_name",type="varchar",length = 3)
private String name;
@FieldC(columnName = "db_id",type="int",length = 10)
private int id;
@FieldC(columnName = "db_age",type="int",length = 10)
private int age;
public UserInfo() {
}
public UserInfo(String name, int id, int age) {
this.name = name;
this.id = id;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface TableC{
String value();
}
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface FieldC{
String columnName();
String type();
int length();
}