类加载、反射、自定义注解

一、类加载过程

类装载:classLoader加载class文件到内存中,并创建class对象

链接:(验证、准备、解析)验证内部结构、类变量分配空间且初始化默认值、符号引用替换到直接引用;

初始化:初始化类变量

http://blog.csdn.net/gjanyanlig/article/details/6818655

二、反射

Class类:用来描述类的内部结构的类。Class对象:包含一个类内部结构信息的对象。

package classLoadAndReflect;

import classLoadAndReflect.MyClassLoader;
import java.lang.Class;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MyReflect {
	public static void main(String[] args) throws Exception {

		// 获取类的Class对象,包含类的“结构信息”
		Class c1 = Class.forName("classLoadAndReflect.MyClassLoader");
		Class c2 = MyClassLoader.class;
		Class c3 = (new MyClassLoader()).getClass();
		System.out.println(c1.getName());
		//通过Class对象创建类的实例
		MyClassLoader loader = (MyClassLoader) c1.newInstance();
		loader.A(222);
		//通过Class对象创建Method对象,利用“主调对象”调用方法
		Method method = c1.getMethod("A", int.class);
		method.invoke(loader, 11111);
		//通过Class对象创建Field对象,设置“对象”成员变量的值
		Field field = c1.getDeclaredField("a");
		field.setInt(loader, 8888);
		//获取方法上的注解信息
		MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
		String description = annotation.getDescribe();
		System.out.println(description);
	}
}
classLoadAndReflect.MyClassLoader
222
11111
默认注解

三、自定义注解

通过自定义注解,可以在类、方法上添加控制信息。

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented 
public @interface MyAnnotation {
	public String getDescribe() default "默认注解";
}
@MyAnnotation(getDescribe = "后来添加在方法上的注解")
public void A(int x){
	System.out.println(x);
}
//获取方法上的注解信息
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
String description = annotation.getDescribe();
System.out.println(description);

http://gityuan.com/2016/01/23/java-annotation/

http://www.jianshu.com/p/a08e7e9ed765






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值