反射是java中的非常重要的一项机制,也称做reflection。它让java在运行中对自身进行检查,并能直接操作程序的内部属性或方法。

反射机制中常用的类

Reflection api中的内部信息有很多包括:package、 type parameters、 superclass、 implemented interfaces、 inner classes、 outer classes、 fields、 constructors、 methods、 modifiers等

常用的类主要包括:

  1. Class:标示某个具体的类或接口
  2. Constructor:封装了类的构造方法
  3. Method:提供关于类或接口的方法的信息
  4. Field:提供有关类或接口的属性信息,以及对他的动态访问权限

Class类:

Class本身就是一个类,Class是该类的名称,也是反射的起点;

获取Class的方法有:

  • getClass():调用通过指定类的对象调用;如:Class cl=str.getClass() 假设str是String对象,类属性为String
  • getSuperClass():通过Class类调用;如:Class clsup=cl.getSuperClass() 因为String的父类为Object,此去得到类属性为Object
  • Class.forName():Class中的静态方法,通过将类名当参数调用:如Class cl2=Class.forName("java.lang.String");注意:此去加载类
  • .Class:通过类名进行调用:如:Class cl3=String.Class;注意:此去不加载类
  • 基本类型TYPE语法:包装类的调用方法:Class cl4=Integer.TYPE

主要的方法有:

1,public static Class<?> forName(String className) :natice 方法,动态加载类。非常重要。
如在sql中动态加载驱动程序:class.forName(sqlDriver);
2,public T newInstance() :根据对象的class新建一个对象,用于反射。非常重要。
可用在反射中构建对象,调用对象方法:
class doubleClass= class.forName("java.lang.Double");
Object objDouble = doubleClass.newInstance();
如在javaBean中就应用了这个方法,因为java默认要有一个无参构造函数。
3, public ClassLoader getClassLoader() :获得类的类加载器Bootstrap ,Extension ,System or user custom ClassLoader(一般为system classloader)。重要。
4,public String getName() :获取类或接口的名字。记住enum为类,annotation为接口。重要
5,public native Class getSuperclass():获取类的父类,继承了父类则返回父类,否则返回java.lang.Object。返回Object的父类为空-null。一般
6,public java.net.URL getResource(String name) :根据字符串获得资源。
7,其他类
public boolean isEnum() :判断是否为枚举类型。
public native boolean isArray() :判断是否为数组类型。
public native boolean isPrimitive() :判断是否为基本类型。
public boolean isAnnotation() :判断是否为注解类型。
public Package getPackage() :反射中获得package,如java.lang.Object 的package为java.lang。
public native int getModifiers() : 反射中获得修饰符,如public static void等 。
public Field getField(String name):反射中获得域成员。
public Field[] getFields() :获得域数组成员。
public Method[] getMethods() :获得方法。
public Method getDeclaredMethod(String name, Class<?>... parameterTypes):加个Declared代表本类,继承,父类均不包括。
public Constructor<?>[] getConstructors() :获得所有的构造函数。

Constructor类

获取构造器的方法:在Class类中提供的方法;

  • Constructor getConstructor(Class[] params) 根据构造函数的参数,返回一个具体的具有public属性的构造函数
  • Constructor getConstructors() 返回所有具有public属性的构造函数数组
  • Constructor getDeclaredConstructor(Class[] params) 根据构造函数的参数,返回一个具体的构造函数(不分public和非public属性)
  • Constructor getDeclaredConstructors() 返回该类中所有的构造函数数组(不分public和非public属性)

主要的方法有:

public String getName() :获取构造器的名字。
public native int getModifiers() : 反射中获得修饰符,如public static void等 。
getParameterTypes():获得参数的属性
newInstance(Object... initargs):使用构造器创建实例

Method类:

和获取构造器方法相同也有四种方法:

  • Method getMethod(String name, Class[] params) 根据方法名和参数,返回一个具体的具有public属性的方法
  • Method[] getMethods() 返回所有具有public属性的方法数组.包括从父类继承的public方法和实现接口的public方法
  • Method getDeclaredMethod(String name, Class[] params) 根据方法名和参数,返回一个具体的方法(不分public和非public属性)
  • Method[] getDeclaredMethods() 返回该类中的所有的方法数组(不分public和非public属性)不包括从父类继承的方法。

主要的方法有:


public String getName() :获取构造器的名字。
public native int getModifiers() : 反射中获得修饰符,如public static void等 。
getParameterTypes():获得参数的属性
getReturnType():获得返回值的属性
invoke(Object obj, Object... args):第一个参数为该方法的对象,第二个为参数;最重要的方法;

Field类:

获取Field的方法:在Class类中提供的方法;

  • Field getField(String name) 根据变量名,返回一个具体的具有public属性的成员变量
  • Field[] getFields() 返回具有public属性的成员变量的数组
  • Field getDeclaredField(String name) 根据变量名,返回一个成员变量(不分public和非public属性)
  • Field[] getDelcaredField() 返回所有成员变量组成的数组(不分public和非public属性)

主要方法有:Field类方法比较多,就不翻译了,不过完全可以通过名字知道用法

Object    get(Object obj)
Returns the value of the field represented by this Field, on the specified object. boolean getBoolean(Object obj)
Gets the value of a static or instance boolean field. byte getByte(Object obj)
Gets the value of a static or instance byte field. char getChar(Object obj)
Gets the value of a static or instance field of type char or of another primitive type convertible to type char via a widening conversion. Class<?> getDeclaringClass()
Returns the Class object representing the class or interface that declares the field represented by this Fieldobject. double getDouble(Object obj)
Gets the value of a static or instance field of type double or of another primitive type convertible to type doublevia a widening conversion. float getFloat(Object obj)
Gets the value of a static or instance field of type float or of another primitive type convertible to type floatvia a widening conversion. Type getGenericType()
Returns a Type object that represents the declared type for the field represented by this Field object. int getInt(Object obj)
Gets the value of a static or instance field of type int or of another primitive type convertible to type int via a widening conversion. long getLong(Object obj)
Gets the value of a static or instance field of type long or of another primitive type convertible to type long via a widening conversion. int getModifiers()
Returns the Java language modifiers for the field represented by this Field object, as an integer. String getName()
Returns the name of the field represented by this Field object. short getShort(Object obj)
Gets the value of a static or instance field of type short or of another primitive type convertible to type shortvia a widening conversion. Class<?> getType()
Returns a Class object that identifies the declared type for the field represented by this Field object. boolean isEnumConstant()
Returns true if this field represents an element of an enumerated type; returns false otherwise. boolean isSynthetic()
Returns true if this field is a synthetic field; returns false otherwise. void set(Object obj, Object value)
Sets the field represented by this Field object on the specified object argument to the specified new value. void setBoolean(Object obj, boolean z)
Sets the value of a field as a boolean on the specified object. void setByte(Object obj, byte b)
Sets the value of a field as a byte on the specified object. void setChar(Object obj, char c)
Sets the value of a field as a char on the specified object. void setDouble(Object obj, double d)
Sets the value of a field as a double on the specified object. void setFloat(Object obj, float f)
Sets the value of a field as a float on the specified object. void setInt(Object obj, int i)
Sets the value of a field as an int on the specified object. void setLong(Object obj, long l)
Sets the value of a field as a long on the specified object. void setShort(Object obj, short s)
Sets the value of a field as a short on the specified object. String toGenericString()
Returns a string describing this Field, including its generic type.

简要演示如下,详情看注释:

package net.peace.ref;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Stack; public class TestRef { public static void main(String[] args) {
// TODO Auto-generated method stub
//Stack<E>
try {
//装载指定的类
Class<Stack> c=(Class<Stack>) Class.forName("java.util.Stack");
//获得指定类名的方法;
Method ms[]=c.getDeclaredMethods();
//判断是否属于特定的类
System.out.println(c.isInstance(new Stack<>()));
for(Method m:ms){
//获得方法的一些信息;
System.out.println(m.getModifiers()+" "+m.getReturnType()+" "+m.getName());
//获得参数属性类
Class[] cc=m.getParameterTypes();
for(Class p:cc){
//获得类名
System.out.println(p.getName());
}
//获得异常类
Class[] ce=m.getExceptionTypes();
for(Class p:ce){
System.out.println(p.getName());
}
}
System.out.println("******************************");
//获得构造器方法
Constructor<Stack>[] con=(Constructor<Stack>[]) c.getDeclaredConstructors();
for(Constructor p:con){
System.out.println(p);
}
System.out.println("******************************");
//获取域
Field[] field=c.getDeclaredFields();
for(Field f:field){
System.out.println(f);
}
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("******************************");
try {
//通过反射创建不是默认对象的构造器
Class list=Class.forName("java.util.ArrayList");
//参数类型设置
Class ps[]=new Class[1];
ps[0]=Integer.TYPE;
//获得对应参数的构造器
Constructor cons=list.getConstructor(ps);
//通过调用构造器构建对象
Integer[] os={3};
ArrayList t=( ArrayList)cons.newInstance(os);
t.add(1);
System.out.println(t.size());
//利用反射调用方法
//创建参数
Class ps3[]= new Class[1];
ps3[0]=Object.class;
//获得想要的方法 add
Method method1=list.getDeclaredMethod("add", ps3);
//进行调用 添加一个元素2;
method1.invoke(t, 2);//第一个参数是对象,第二个参数是方法参数;
///调用另外一个构造方法
Class ps2[]=new Class[1];
ps2[0]=Collection.class;
Constructor cons2=list.getConstructor(ps2);
ArrayList t2=( ArrayList)cons2.newInstance(t);
System.out.println(t2); } catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} } }

java反射介绍的更多相关文章

  1. Java动态程序设计:反射介绍

    使用运行的类的信息使你的程序设计更加灵活 反射授予了你的代码访问装载进JVM内的Java类的内部信息的权限,并且允许你编写在程序执行期间与所选择的类的一同工作的代码,而不是在源代码中.这种机制使得反射 ...

  2. Java 反射机制介绍

    参考文章:http://www.cnblogs.com/skywang12345/p/3345205.html Java 反射机制.通俗来讲呢,就是在运行状态中,我们可以根据“类的部分已经的信息”来还 ...

  3. java反射机制的简单介绍

    参考博客: https://blog.csdn.net/mlc1218559742/article/details/52754310 先给出反射机制中常用的几个方法: Class.forName (& ...

  4. Java反射详细介绍

    反射 目录介绍 1.反射概述 1.1 反射概述 1.2 获取class文件对象的三种方式 1.3 反射常用的方法介绍 1.4 反射的定义 1.5 反射的组成 1.6 反射的作用有哪些 2.反射的相关使 ...

  5. Java反射机制介绍

    1. 文档概述 Java反射是Java被视为动态(或准动态)语言的一个关键性质,Java反射机制容许程序在运行时加载.探知.使用编译期间完全未知的classes.换言之,Java可以加载一个运行时才得 ...

  6. java反射机制简单介绍

    1.字节码.所谓的字节码就是当java虚拟机载入某个类的对象时,首先须要将硬盘中该类的源码编译成class文件的二进制代码(字节码),然后将class文件的字节码载入到内存中,之后再创建该类的对象 2 ...

  7. Android 插件化开发(一):Java 反射技术介绍

    写在前面:学习插件化开发推荐书籍<Android 插件化开发指南>,本系列博客所整理知识部分内容出自此书. 在之前的项目架构的博文中,我们提到了项目插件化架构,提到插件化架构不得不提的到J ...

  8. java反射学习之二万能EXCEL导出

    一.EXCEL导出的实现过程 假设有一个对象的集合,现在需要将此集合内的所有对象导出到EXCEL中,对象有N个属性:那么我们实现的方式是这样的: 循环这个集合,在循环集合中某个对象的所有属性,将这个对 ...

  9. java反射学习之一反射机制概述

    一.反射机制背景概述 1.反射(reflection)是java被视为动态语言的一个关键性质 2.反射机制指的是程序在运行时能获取任何类的内部所有信息 二.反射机制实现功能概述 1.只要给定类的全名, ...

随机推荐

  1. 【LA3523 训练指南】圆桌骑士 【双连通分量】

    题意 有n个骑士经常举行圆桌会议,商讨大事.每次圆桌会议至少应有3个骑士参加,且相互憎恨的骑士不能坐在圆桌旁的相邻位置.如果发生意见分歧,则需要举手表决,因此参加会议的骑士数目必须是奇数,以防赞同和反 ...

  2. 【bzoj2480】Spoj3105 Mod

    2480: Spoj3105 Mod Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 557  Solved: 210[Submit][Status][ ...

  3. Nginx源码完全注释(4)ngx_queue.h / ngx_queue.c

    队列头文件ngx_queue.h #include <ngx_config.h> #include <ngx_core.h> #ifndef _NGX_QUEUE_H_INCL ...

  4. 常见的APP性能测试指标

    性能测试在软件的质量保证中起着重要的作用,它包括的测试内容丰富多样.中国软件评测中心将性能测试概括为三个方面:应用在客户端性能的测试.应用在网络上性能的测试和应用在服务器端性能的测试.通常情况下,三方 ...

  5. 查看并解除Oracle锁

    当某个数据库用户在数据库中插入.更新.删除一个表的数据,或者增加一个表的主键时或者表的索引时, 常常会出现ora-00054:resource busy and acquire with nowait ...

  6. 3.1.6 循环栅栏:CyclicBarrier

    package 第三章.循环栅栏CyclicBarrier; import java.util.concurrent.BrokenBarrierException;import java.util.c ...

  7. MP3 Lame 转换 参数 设置(转)

    我们在对音频格式的转换中,打交道最多的就是MP3了.如果你能彻底玩转MP3,那么对你的音频创作和对其他音频格式的掌握会有很大的帮助.下面我们给大家介绍MP3制作软件:LAME 要制作出高音质的MP3靠 ...

  8. eclipse查看jar包中的class文件出现乱码

    参考:http://blog.csdn.net/bell2008/article/details/40978959 1,问题来源是在eclipse中直接查看springside的class(由ecli ...

  9. 手动安装Chrome截屏控件扩展-Xproer.ScreenCapture(ScreenCapture.crx)

    1.打开扩展面板,在地址栏中输入 chrome://extensions   或通过"扩展程序"菜单打开   2.将ScreenCapture.crx拖拽到此面板中   3.选择添 ...

  10. SOAP协议初级指南 (三)

    独立元素 在SOAP中, 一个独立元素表示至少被一个多引用存取元素引用的类型的实例.所有的独立元素用soap:id属性作标记,而且这个属性的值在整个SOAP envelope中必须是唯一的.独立的元素 ...