基础技能之反射

  • 定义        
Java反 射主要提供的功能有:在运行时判断任意一个对象所属的类;在运行时构建任意一个类的对象;在运行时判断任意一个类所具有的成员变量和方法、注解;在运行时调用任意一个对象的方法;生成动态代理。

 

示例代码如下:

 

package baseKnowledge;

import java.lang.annotation.Annotation;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class ReflectionTest {
	public static void main(String[] args) {

		try {
			I i = new A();
			System.out.println(i.getClass());// class baseKnowledge.A
												// 获取的是运行时的class

			Class clazz = Class.forName("baseKnowledge.A");
			A a = (A) clazz.newInstance(); // 构造运行时的对象
			a.p();

			System.out.println("\n==========getConstructors=============");
			Constructor[] cs = clazz.getConstructors();// 只能获取public修饰的字段,以及父类public字段
			for (Constructor c : cs) {
				System.out.print(c.getParameterTypes().length + " | ");// 2 |
			}

			System.out.println("\n==========getConstructors=============");
			Constructor[] cs2 = clazz.getDeclaredConstructors();// 只能获取public修饰的字段,以及父类public字段
			for (Constructor c : cs2) {
				System.out.print(c.getParameterTypes().length + " | ");// 0 | 1
																		// | 3 |
																		// 2 |
			}

			System.out.println("\n==========getFields=============");
			Field[] fs = clazz.getFields();// 只能获取public修饰的字段,以及父类public字段
			for (Field f : fs) {
				System.out.print(f.getName() + " | ");// puF_a | pa_pub_f |
			}
			System.out.println("\n=========getDeclaredFields==============");
			Field[] fs2 = clazz.getDeclaredFields();// 只能获取自己的所有字段(不包括父类)
			for (Field f : fs2) {
				System.out.print(f.getName() + " | ");// puF_a | deF_a | proF_a
														// | priF_a |
			}
			System.out.println("\n=========getMethods==============");
			Method[] ms = clazz.getMethods();// 可以获取自己以及父类的public方法
			for (Method m : ms) {
				System.out.print(m.getName() + " | ");// p | methodA | getClass
														// | hashCode | equals |
														// toString | notify |
														// notifyAll | wait |
														// wait | wait |
			}

			System.out.println("\n=======getDeclaredMethods================");
			Method[] ms2 = clazz.getDeclaredMethods();// 只能获取自己的所有发方法(不包括父类)
			for (Method m : ms2) {
				System.out.print(m.getName() + " | ");// p2 | p3 | p4 | p |
			}

			System.out.println("\n=======getAnnotations================");
			Annotation[] as = clazz.getAnnotations();// 获取包含父类的注解,此注解必须是@Inherited以及@Retention(RetentionPolicy.RUNTIME)类型
			for (Annotation an : as) {
				System.out.print(an.annotationType() + " | ");// interface
																// baseKnowledge.an
																// |
			}

			System.out.println("\n=======getDeclaredAnnotations================");
			Annotation[] as2 = clazz.getDeclaredAnnotations();// 获取自己的注解
			for (Annotation an : as2) {
				System.out.print(an.annotationType() + " | ");//
			}

		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

interface I {
	public void p();
}

class A extends parent implements I {
	public String puF_a;
	String deF_a;
	protected String proF_a;
	private String priF_a;

	A() {

	}

	private A(String a) {

	}

	protected A(String a, String b, String c) {

	}

	public A(String a, String b) {

	}

	@Override
	public void p() {
		System.out.println("public  method p ");

	}

	private void p2() {
		System.out.println("private method  p2");
	}

	void p3() {
		System.out.println(" method  p3");
	}

	protected void p4() {
		System.out.println("protected method  p4");
	}

}

@an("")
class parent {
	protected String pa_pro_f;
	String pa_def_f;
	public String pa_pub_f;
	private String pa_pri_f;

	public void methodA() {
		System.out.println("public methodA");
	}

	void methodB() {
		System.out.println("public methodB");
	}

	protected void methodC() {
		System.out.println("protected methodC");
	}

	private void methodD() {
		System.out.println("private methodD");
	}

}

class B implements I {

	@Override
	public void p() {
		System.out.println("class B");

	}

}

@Retention(RetentionPolicy.RUNTIME) // 这种类型的Annotations将被JVM保留,所以他们能在运行时被JVM或其他使用反射机制的代码所读取和使用.
@Inherited // 允许子类继承父类的注解。
@interface an {

	String value();
}

 

 

  •  常用的反射的API
  1、构造方法       Constructor[] getConstructors()  获取public构造的所有方法       Constructor getConstructor(Class... parameterTypes)  获取public且传入方法参数类型和构造方法参数类型一一对应的构造方法         Constructor[]    getDeclaredConstructors() 获取本类所有的构造方法       Constructor getDeclaredConstructor( Class... parameterTypes)  获取传入方法参数类型和构造方法参数类型一一对应的构造方法,不论该构造方法是否是public修饰       Field[] getFields()  获取所有public修饰的字段,包括其继承的字段       Field getField(String  name)  获取指定字段名称的所有且包括继承的public修饰的字段        Field []    getDeclaredField s()  获取本类自己的所有的字段       Field   get Declared Field (String  name)   获取本类指定的名称的字段,无论是否为public修饰的字段 注:字段名称区分大小写       Method getMethod(String  name,Class... parameterTypes)  获取指定方法名称以及方法参数类型的方法。该方法为public修饰的,可以是其继承的public方法。         Method[]    getDeclared Methods()  获取本类自己的所有的方法       Method  get Declared Method(String  name, Class ... parameterTypes 获取 指定方法名称以及方法参数类型的方法。该方法只能为 本类自己的所有的方法 注:字段名称区分大小写   4、注解
       Annotation[] getAnnotations()  获取所有修饰的以及继承的注解
      Annotation getAnnotation(Class   parameterTypes)  获取该类指定的注解
       Annotation []   getDeclaredAnnotation ()  获取本类的所有的注解
    注:只有被@Inherited 标注过的注解,才能被子类继承;只有被@Retention(RetentionPolicy.RUNTIME)标注过的注解,才能被JVM保留,才能在运行时,被JVM获取其他的使用反射机制的代码读取和使用。因此,只有同时被这两种注解标注过的注解,才可以从父类中继承到。
5、初始化对象
Object newInstance()  只有含有非private修饰无参的构造方法,才可以使用此方法去构造对象。
 
 

 

 

 

 

      Annotation getAnnotation(Class   parameterTypes)  获取该类指定的注解        Annotation []   getDeclaredAnnotation ()  获取本类的所有的注解     注:只有被@Inherited 标注过的注解,才能被子类继承;只有被@Retention(RetentionPolicy.RUNTIME)标注过的注解,才能被JVM保留,才能在运行时,被JVM获取其他的使用反射机制的代码读取和使用。因此,只有同时被这两种注解标注过的注解,才可以从父类中继承到。  

猜你喜欢

转载自ruxia2010.iteye.com/blog/2237532