JAVA反射机制详解(转载)

动态语言

  动态语言
  程序运行      可以  改变  程序结构    变量  类型。典型的语言:
  Python    ruby    javascript  等。

如下javascript代码:

 

1
2
3
4
function test(){
           var s = "var a=3;var b=5;alert(a+b);" ;
           eval(s);
}

C,  C++,  JAVA不是动态语言JAVA可以称之为“准动态语言”。但是JAVA有一定的动态性,我们可以利用反射机制、字节码操作获得类似动态语言的特性。

JAVA的动态性让编程的时候更加灵活!

反射机制介绍

  反射机制
  指的是可以于运行时加载、探知、使用编译期间完全未知的类 
  程序在运行状态中,可以动态加载一个只有名称的类,对于  任意一  个已加载的类,  都能够知道这个类的所有属性和方法;对于任意一个对象,都能够调用它的任意一个方法和属性 

               Class  c = Class.forName("com.bjsxt.test.User");

  加载完类之后,在堆内存中,就产生了一个   Class   类型的对象(一个类只有一个   Class   对象),这个对象就包含了完整的类的结构信息。我们可以通过这个对象看到类的结构。这个对象就像一面镜子,透过这个镜子  看到类  的结构,所以,我们形象的称之为:反射。 

Class类介绍

• java.lang.Class类十分特殊,用来表示java中类型(class/interface/enum/annotation       /primitive type/void)本身。

Class类的对象包含了某个被加载类的结构。一个被加载的类对应一个Class对象。

一个class被加载,或当加载器(class loader)的defineClass()JVM调用,JVM 便自动产生一个Class 对象

Class类是Reflection的根源。

针对任何您想动态加载、运行的类,唯有先获得相应的Class 对象

Class类的对象如何获取?

运用getClass()

运用Class.forName()最常被使用

运用.class 语法

课堂代码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
package com.bjsxt.test.bean;
 
public class User {
     
     private int id;
     private int age;
     private String uname;
     
     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;
     }
     public String getUname() {
         return uname;
     }
     
     public void setUname(String uname) {
         this .uname = uname;
     }
     
     public void setUname() {
         this .uname = "高淇" ;
     }
     
     public User( int id, int age, String uname) {
         super ();
         this .id = id;
         this .age = age;
         this .uname = uname;
     }
     
     //javabean必须要有无参的构造方法!
     public User() {
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.bjsxt.test;
 
/**
  * 测试各种类型(class,interface,enum,annotation,primitive type,void)对应的java.lang.Class对象的获取方式
  * @author 尚学堂高淇    www.sxt.cn
  *
  */
@SuppressWarnings ( "all" )
public class Demo01 {
     
     public static void main(String[] args) {
         String path = "com.bjsxt.test.bean.User" ;
         
         try {
             
             Class clazz = Class.forName(path);
             //对象是表示或封装一些数据。  一个类被加载后,JVM会创建一个对应该类的Class对象,类的整个结构信息会放到对应的Class对象中。
             //这个Class对象就像一面镜子一样,通过这面镜子我可以看到对应类的全部信息。
             System.out.println(clazz.hashCode());
             
             Class clazz2 = Class.forName(path); //一个类只对应一个Class对象
             System.out.println(clazz2.hashCode());
             
             Class strClazz = String. class ;
             Class strClazz2 = path.getClass();
             System.out.println(strClazz==strClazz2);
             
             Class intClazz = int . class ;
             
             int [] arr01 = new int [ 10 ];
             int [][] arr02 = new int [ 30 ][ 3 ];
             int [] arr03 = new int [ 30 ];
             double [] arr04 = new double [ 10 ];
             
             System.out.println(arr01.getClass().hashCode());
             System.out.println(arr02.getClass().hashCode());
             System.out.println(arr03.getClass().hashCode());
             System.out.println(arr04.getClass().hashCode());
             
             
         } catch (Exception e) {
             e.printStackTrace();
         }
         
     }
     
}

 

反射机制动态调用构造器、方法、属性

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.bjsxt.test;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
 
/**
  * 应用反射的API,获取类的信息(类的名字、属性、方法、构造器等)
  * @author 尚学堂高淇  www.sxt.cn
  *
  */
public class Demo02 {
     public static void main(String[] args) {
         String path = "com.bjsxt.test.bean.User" ;
         
         try {
             Class clazz = Class.forName(path);
             
             //获取类的名字
             System.out.println(clazz.getName()); //获得包名+类名:com.bjsxt.test.bean.User
             System.out.println(clazz.getSimpleName());  //获的类名:User
             
             //获取属性信息
//          Field[] fields = clazz.getFields(); //只能获得public的field
             Field[] fields = clazz.getDeclaredFields(); //获得所有的field
             Field f = clazz.getDeclaredField( "uname" );
             System.out.println(fields.length);
             for (Field temp:fields){
                 System.out.println( "属性:" +temp);
             }
             //获取方法信息
             Method[] methods = clazz.getDeclaredMethods();
             Method m01 = clazz.getDeclaredMethod( "getUname" , null );
             //如果方法有参,则必须传递参数类型对应的class对象
             Method m02 = clazz.getDeclaredMethod( "setUname" , String. class );
             for (Method m:methods){
                 System.out.println( "方法:" +m);
             }
             
             //获得构造器信息
             Constructor[] constructors = clazz.getDeclaredConstructors();
             Constructor c = clazz.getDeclaredConstructor( int . class , int . class ,String. class );
             System.out.println( "获得构造器:" +c);
             for (Constructor temp:constructors){
                 System.out.println( "构造器:" +temp);
             }
             
             
         } catch (Exception e) {
             e.printStackTrace();
         }
     }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
package com.bjsxt.test;
 
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
 
import com.bjsxt.test.bean.User;
 
/**
  * 通过反射API动态的操作:构造器、方法、属性
  * @author 尚学堂高淇 www.sxt.cn
  *
  */
public class Demo03 {
     public static void main(String[] args) {
 
         String path = "com.bjsxt.test.bean.User" ;
         
         try {
             Class<User> clazz = (Class<User>) Class.forName(path);
             
             //通过反射API调用构造方法,构造对象
             User u = clazz.newInstance();   //其实是调用了User的无参构造方法
             System.out.println(u);
             
             Constructor<User> c = clazz.getDeclaredConstructor( int . class , int . class ,String. class );
             User u2 = c.newInstance( 1001 , 18 , "高淇二" );
             System.out.println(u2.getUname());
             
             //通过反射API调用普通方法
             User u3 = clazz.newInstance();
             Method method = clazz.getDeclaredMethod( "setUname" , String. class );
             method.invoke(u3, "高淇三" );   //u3.setUname("高淇三");
             System.out.println(u3.getUname());
             
             //通过反射API操作属性
             User u4 = clazz.newInstance();
             Field f = clazz.getDeclaredField( "uname" );
             f.setAccessible( true ); //这个属性不需要做安全检查了,可以直接访问
             f.set(u4, "高淇四" );       //通过反射直接写属性
             System.out.println(u4.getUname());  //通过反射直接读属性的值
             System.out.println(f.get(u4));
             
             
         } catch (Exception e) {
             e.printStackTrace();
         }
     
         
     }
}

反射操作泛型

Java采用泛型擦除的机制来引入泛型。Java中的泛型仅仅是给编译器javac使用的,确保数据的安全性和免去强制类型转换的麻烦。但是,一旦编译完成,所有的和泛型有关的类型全部擦除

为了通过反射操作这些类型以迎合实际开发的需要,Java新增了ParameterizedTypeGenericArrayTypeTypeVariable WildcardType几种类型来代表不能被归一到Class类中的类型但是又和原始类型齐名的类型

ParameterizedType表示一种参数化的类型,比如Collection<String>

GenericArrayType表示一种元素类型参数化类型或者类型变量数组类型

TypeVariable各种类型变量的公共父接口

WildcardType代表一种通配符类型表达式,比如?, ? extends Number, ? super Integer【wildcard是一个单词:就是“通配符”

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.bjsxt.test;
 
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
 
import com.bjsxt.test.bean.User;
 
/**
  * 通过反射获取泛型信息
  * @author dell
  *
  */
public class Demo04 {
     
     public void test01(Map<String,User> map,List<User> list){
         System.out.println( "Demo04.test01()" );
     }
     
     public Map<Integer,User> test02(){
         System.out.println( "Demo04.test02()" );
         return null ;
     }
     
     public static void main(String[] args) {
 
         try {
             
             //获得指定方法参数泛型信息
             Method m = Demo04. class .getMethod( "test01" , Map. class ,List. class );
             Type[] t = m.getGenericParameterTypes();
             for (Type paramType : t) {
                 System.out.println( "#" +paramType);
                 if (paramType instanceof ParameterizedType){
                     Type[] genericTypes = ((ParameterizedType) paramType).getActualTypeArguments();
                     for (Type genericType : genericTypes) {
                         System.out.println( "泛型类型:" +genericType);
                     }
                 }
             }
             
             //获得指定方法返回值泛型信息
             Method m2 = Demo04. class .getMethod( "test02" , null );
             Type returnType = m2.getGenericReturnType();
             if (returnType instanceof ParameterizedType){
                     Type[] genericTypes = ((ParameterizedType) returnType).getActualTypeArguments();
 
                     for (Type genericType : genericTypes) {
                         System.out.println( "返回值,泛型类型:" +genericType);
                     }
                     
             }
             
             
         } catch (Exception e) {
             e.printStackTrace();
         }
     
         
     
     }
}

 

通过反射操作注解

可以通过反射API:getAnnotations, getAnnotation获得相关的注解信息

课堂代码(定义泛型)

1
2
3
4
5
6
7
8
9
10
11
12
package com.bjsxt.test.annotation;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target (value={ElementType.TYPE})
@Retention (RetentionPolicy.RUNTIME)
public @interface SxtTable {
     String value();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
package com.bjsxt.test.annotation;
 
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target (value={ElementType.FIELD})
@Retention (RetentionPolicy.RUNTIME)
public @interface SxtField {
     String columnName();
     String type();
     int length();
}

课堂代码(类中使用注解)

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
package com.bjsxt.test.annotation;
 
@SxtTable ( "tb_student" )
public class SxtStudent {
     
     @SxtField (columnName= "id" ,type= "int" ,length= 10 )
     private int id;
     @SxtField (columnName= "sname" ,type= "varchar" ,length= 10 )
     private String studentName;
     @SxtField (columnName= "age" ,type= "int" ,length= 3 )
     private int age;
     
     
     public int getId() {
         return id;
     }
     public void setId( int id) {
         this .id = id;
     }
     public String getStudentName() {
         return studentName;
     }
     public void setStudentName(String studentName) {
         this .studentName = studentName;
     }
     public int getAge() {
         return age;
     }
     public void setAge( int age) {
         this .age = age;
     }
     
     
}

反射读取类中注解    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package com.bjsxt.test;
 
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
 
import com.bjsxt.test.annotation.SxtField;
import com.bjsxt.test.annotation.SxtTable;
 
/**
  * 通过反射获取注解信息
  * @author 尚学堂高淇
  *
  */
public class Demo05 {
     public static void main(String[] args) {
 
         try {
             Class clazz = Class.forName( "com.bjsxt.test.annotation.SxtStudent" );
             
             //获得类的所有有效注解
             Annotation[] annotations=clazz.getAnnotations();
             for (Annotation a : annotations) {
                 System.out.println(a);
             }
             //获得类的指定的注解
             SxtTable st = (SxtTable) clazz.getAnnotation(SxtTable. class );
             System.out.println(st.value());
             
             //获得类的属性的注解
             Field f = clazz.getDeclaredField( "studentName" );
             SxtField sxtField = f.getAnnotation(SxtField. class );
             System.out.println(sxtField.columnName()+ "--" +sxtField.type()+ "--" +sxtField.length());
             
             //根据获得的表名、字段的信息,拼出DDL语句,然后,使用JDBC执行这个SQL,在数据库中生成相关的表
             
         } catch (Exception e) {
             e.printStackTrace();
         }
         
     
     }
}

 

 

反射机制性能问题

setAccessible

启用和禁用访问安全检查的开关,值为 true 则指示反射的对象在使用时应该取消 Java 语言访问检查。值为 false 则指示反射的对象应该实施 Java 语言访问检查。并不是true就能访问为false就不能访问。

禁止安全检查,可以提高反射的运行速度。

可以考虑使用:cglib/javaassist字节码操作

课堂代码:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package com.bjsxt.test;
 
import java.lang.reflect.Method;
 
import com.bjsxt.test.bean.User;
 
/**
  * 通过跳过安全检查,提高反射效率
  * 三种执行方法的效率差异比较
  *
  * @author 尚学堂高淇 www.sxt.cn
  *
  */
public class Demo06 {
     
     public static void test01(){
         User u = new User();
         
         long startTime = System.currentTimeMillis();
         
         for ( int i = 0 ; i < 1000000000L; i++) {
             u.getUname();
         }
         
         long endTime = System.currentTimeMillis();
         System.out.println( "普通方法调用,执行10亿次,耗时:" +(endTime-startTime)+ "ms" );
     }
     
     public static void test02() throws Exception{
         User u = new User();
         Class clazz = u.getClass();
         Method m = clazz.getDeclaredMethod( "getUname" , null );
//      m.setAccessible(true);
         
         long startTime = System.currentTimeMillis();
         
         for ( int i = 0 ; i < 1000000000L; i++) {
             m.invoke(u, null );
         }
         
         long endTime = System.currentTimeMillis();
         System.out.println( "反射动态方法调用,执行10亿次,耗时:" +(endTime-startTime)+ "ms" );
     }
     
     public static void test03() throws Exception{
         User u = new User();
         Class clazz = u.getClass();
         Method m = clazz.getDeclaredMethod( "getUname" , null );
         m.setAccessible( true );  //不需要执行访问安全检查
         
         long startTime = System.currentTimeMillis();
         
         for ( int i = 0 ; i < 1000000000L; i++) {
             m.invoke(u, null );
         }
         
         long endTime = System.currentTimeMillis();
         System.out.println( "反射动态方法调用,跳过安全检查,执行10亿次,耗时:" +(endTime-startTime)+ "ms" );
     }
     
     
     public static void main(String[] args) throws Exception {
         test01();
         test02();
         test03();
     }
}
执行结果:

 

1
2
3
普通方法调用,执行 10 亿次,耗时:2218ms
反射动态方法调用,执行 10 亿次,耗时:63427ms
反射动态方法调用,跳过安全检查,执行 10 亿次,耗时:14335ms

 

 

显然,通过测试我们发现反射比普通方法调用效率大大降低,但是可以通过禁止访问安全检查提高效率。万事都有利弊,反射降低了运行效率,但是灵活性提高了开发效率。 

http://www.sxt.cn/u/328/blog/4154

猜你喜欢

转载自jsycjacky.iteye.com/blog/2224576