黑马程序员_java基础加强_2

本文详细介绍了Java注解的概念及其常用注解的使用方法,同时阐述了类加载器的工作机制,包括系统默认的三个主要类加载器及其作用。此外,文章还通过实例演示了代理机制的应用,并提供了关于动态代理类的使用方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

------- android培训java培训、期待与您交流!----------
9,注解(jdk1.5的新特性):相当于一种标记,在程序中加了注解就等于为程序打上了某种标记(一个注解就是一个类),标记可以加在包,类,成员变量,方法,方法的参数以及局部变量上。
常用注解:
@Deprecated 过时 (Retention-RUNTIME)
@SuppressWarnings("deprecation")  去掉编译时过时的提醒 (Retention-SOURCE)
@override 是否对父类覆盖  (Retention-SOURCE )
@Retention(SOURCE,CLASS,RUNTIME,) 设置注解的生命周期,默认值是CLASS
@Target()设置注解的位置
注解的返回值的类型:8个基本类型,String,Class,枚举,注解,以及这些类型的数组
示例:
//定义一个注解类
public @interface MetaAnnotation {
	String value();
}
/*定义一个注解类*/
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import cn.itcast.day1.EnumTest;

//元注解(元数据,元信息):在注解上定义注解
@Retention(RetentionPolicy.RUNTIME)//设置注解在哪个阶段(java源文件,class文件,内存字节码中)
@Target({ElementType.METHOD,ElementType.TYPE})//设置注解加载到哪些成分。
public @interface ItcastAnnotation {
	String color() default "blue";//设置默认注解的属性
	String value();
	int[] arrayAttr()default {3,5,4}; //设置注解的默认值
	//枚举类型的属性
	EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;//EnumTest.TrafficLamp这个类是基础加强_1第5个案例使用到的类。
	//注解类型的属性
	MetaAnnotation anntationAttr() default @MetaAnnotation("cyy");
}
//定义一个类,使用将上面定义的注解
import javax.swing.text.StyledEditorKit.ItalicAction;
@ItcastAnnotation(color="red",value="abc",arrayAttr={2,4},anntationAttr=@MetaAnnotation("tc"))
public class AnnotationTest {

	@SuppressWarnings("deprecation")//去掉编译时的过时提醒
	@ItcastAnnotation("xyc")
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		System.runFinalizersOnExit(true);
		
		if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
			ItcastAnnotation annotation = AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
			System.out.println(annotation.color());
			System.out.println(annotation.value());
			System.out.println(annotation.arrayAttr().length);
			System.out.println(annotation.lamp().nextLamp().name());
			System.out.println(annotation.anntationAttr().value());
		}
	}
	@Deprecated//这个方法已过时
	public static void sayHello(){
		System.out.println("hi,tang");
	}
	
}
10,类加载器:
系统默认三个主要的类加载器:
BootStrap:第一个类加载器,不是java类,嵌套在java虚拟机内核中。:jre/lib/rt.jar
ExtClassLoader:加载的目录jre/lib/ext/*.jar
AppClassLoader:加载的目录classpath指定的所有jar或目录
自定义的类加载器必须继承ClassLoader类,覆盖findClass方法

11,代理: 一个角色代表别一个角色来完成某些特定的功能。 
比如:生产商,中间商,客户这三者这间的关系, 客户买产品并不直接与生产商打交道,也不用知道产品是如何产生的,客户只与中间商打交道,而中间商就可以对产品进行一些包装,提供一些售后的服务。 
静态代理:由程序员创建或特定工具自动生成源代码,再对其编译。在程序运行前,代理类的.class文件就已经存在了。 
动态代理:在程序运行时,运用反射机制动态创建而成。 
/*
 * 动态代理类的使用
 * */
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyTest {
	public static void main(String[] args) throws Exception{
		//创建一个Collection类的动态代理类
		Class classProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		System.out.println(classProxy.getName());
		
		//获取动态代理类的构造方法
		System.out.println("--------begin constructor list-----------");
	/**/Constructor[] constructors = classProxy.getConstructors();
		for(Constructor constructor : constructors){
			String name = constructor.getName();
			StringBuilder sbuilder = new StringBuilder();
			sbuilder.append(name);
			sbuilder.append('(');
			Class[] clazzParams = constructor.getParameterTypes();
			for(Class clazzParam : clazzParams){
				sbuilder.append(clazzParam.getName()).append(',');
			}
			if(clazzParams.length!=0 && clazzParams!=null){
				sbuilder.deleteCharAt(sbuilder.length()-1);
			}
			
			sbuilder.append(')');
			System.out.println(sbuilder.toString());
		}
		
		//获取动态代理类的方法
		System.out.println("-------begin method list------------------");
		Method[] methods = classProxy.getMethods();
		for(Method method : methods){
			String name = method.getName();
			StringBuilder sbuilder = new StringBuilder();
			sbuilder.append(name);
			sbuilder.append('(');
			Class[] clazzParams = method.getParameterTypes();
			for(Class clazzParam : clazzParams){
				sbuilder.append(clazzParam.getName()).append(',');
			}
			if(clazzParams.length!=0 && clazzParams!=null){
				sbuilder.deleteCharAt(sbuilder.length()-1);
			}
			
			sbuilder.append(')');
			System.out.println(sbuilder.toString());
		}
		
		//创建动态代理类的对象
		System.out.println("---------begin create instance list-------------");
		//第一种创建动态类对象的方法
		Constructor constructor = classProxy.getConstructor(InvocationHandler.class);
		class MyInvocationHander implements InvocationHandler{
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				return null;
			}	
		}
		Collection proxy = (Collection)constructor.newInstance(new MyInvocationHander());
		System.out.println(proxy);
		proxy.clear();

		//第二种创建动态代理类对象的方法
		Collection proxy1 = (Collection)constructor.newInstance(new InvocationHandler(){
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				return null;
			}
		});
		//第三种创建动态代理类对象的方法
		final ArrayList target = new ArrayList();
		Collection proxy2 = (Collection)getProxy(target,new MyAdvice());
		proxy2.add("abc");
		proxy2.add("def");
		proxy2.add("xyz");
		System.out.println(proxy2.size());
	}
	private static Object getProxy(final Object target,final Advice advice) {
		Collection proxy2 = (Collection)Proxy.newProxyInstance(
							target.getClass().getClassLoader(),
							//new Class[] {Collection.class},
							target.getClass().getInterfaces(),
							new InvocationHandler() {
								@Override
								public Object invoke(Object proxy, Method method, Object[] args)
										throws Throwable {
									
									/*第一种方法
									 * long beginTime = System.currentTimeMillis();
									Object retVal = method.invoke(target, args);
									long endTime = System.currentTimeMillis();
									System.out.println(method.getName()+"  running time is  "+(endTime-beginTime));
									return retVal;*/
									//第二种方法
									advice.beforeMethod(method);
									Object retVal = method.invoke(target, args);
									advice.afterMethod(method);
									return retVal;	
								}
							}
							);
		return proxy2;
	}
}
12,泛型部分的总结在一篇单独的博客中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值