黑马程序员--java高新技术 26--javaBean,泛型,类加载器,代理spring小框架

---------------------- ASP.Net+Android+IO开发S.Net培训、期待与您交流! ----------------------

 

/*设计模式:
Singleton:	单例模式
Factorty:	工厂模式
Iterator:	迭代器模式
Template:	模板模式
Coposite:	组合模式
Proxy:		代理模式
Decrator:	装饰模式
Flyweight:	享元模式
*/

//26-30

class  
{
	public static void main(String[] args) 
	{
		ReflectPoint pt1 = new ReflectPoint(3,5);
		String propertyName = "x";

		Object retVal = getProperty(pt1,propertyName);
		System.out.println("Hello World!");
	}

	private static Object getProperty(Object pt1,String propertyName) throws IntrospectionException,IllegalAccessException,InvocationTargetException{
		PropertyDescriptor pd = new PropertyDescriptor(propertyName,pt1.getClass());
		Method methodGetX = pd.getReadMethod();
		Object retVal = methodGetX.invoke(pt1);
		return retVal;
	}
}

/*26-32 BeanUtils 工具包
r(工程\lib\jar文件)--build path--add to build path  //增加自定义的jar文件 referenced Libraries。
	//jar 文件 直接复制到 lib 文件夹下。

commons-beanutils.jar
commons-logging-1.1.jar

Map map = {name:"ddf",agd:18};
BeanUtils.setProperty(map,"name","adf");

PropertyUtils.setProperty(pt1,"x",9);

BeanUtils 以字符串的类型 对数据进行操作。支持属性链的操作
PropertyUtils 以原有属性类型进行对数据进行操作。
*/

/*26-33
1.5新特性:注解


javac -xlint:deprecation xxx.java	//查看过时的方法
@SuppressWarning("deprecation")  //不提示 已过时信息。
@Deprecated		//用于标记该方法过时了

集合的equals方法 传入的参数是Object类型的参数。

java.lang 的注解
Deprecated
Override
SuppressWarning

加了注解就等于给程序打上了某种标记。

注解可以加在 包,类,成员变量,方法,方法的参数,局部变量
*/

/*26-34
注解相当于 一个特殊的 类

注解的应用
	注解类
	应用了注解的类
	对 应用了注解的类 进行反射的类

AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class);
AnnotationTest.class.getAnnotation(ItcastAnnotation.class);

@Retention(RetentionPolicy.RUNTIME)  //元注解

注解的生命周期:
	源文件,class文件,内存中的字节码
	默认在保留到class文件


@Target({ElementType.METHOD,Element.TYPE})
*/

/*26-35 为注解增加属性
当仅有一个需要赋值的属性是可以省略 "属性="

Annotation annotationAttr default @MetaAnnotation("ihm");  //注解的元素是注解类型的值
*/

/*26-37
泛型是提供给javac使用的

因此通过反射添加数据会穿透泛型限定

Collection<Stirng> c = new Vector(); //为了兼容之前的版本
Collection c = new Vector<String>();

在创建数组实例时,数组元素不能使用参数化的类型。
例: Vector<Integer>vectorList[] = new Vector<Integer>[10];
*/

/*26-40
throw 可以 throw T类型
但是 catch 不能 catch T类型
*/

/*26-41
copy1(new Vector<String>(),new String[10];	//传播性,在类型参数中指明是Data,T就是Data
copy2(new Date[10],new String[10]);	//类型推断, 类型推断首先考虑返回值的类型。

public static <T> void copy1(Collection<T> dest, T[] src){}
public static <T> void copy2(T[] dest, T[] src){};
*/

/*26-42
静态方法不能使用 定义在类上的泛型类型,因为泛型在创建对象时才确定其他具体的类型。

静态方法可以使用定义在方法上的泛型类型
*/

/*26-43
获得参数化类型的方法:

Method applyMethod = GenericTest.class.getMethod("applyVector",Vector.class);
Type[] types = applyMethod.getGenericParameterTypes();
Parameterized pType = (ParameterizedType)types[0];
sop(pType.getRawType());
sop(pType.getActualTypeArguments()[0]);
*/

/*26-44
类加载器:JVM默认有BootStrap,ExtClassLoader,AppClassLoader

BootStrap-->jre/lib/rt.jar
	|
ExtClassLoader-->jre/lib/ext/*.jar
	|
AppClassLoader-->classpath指定的所有jar或目录。

类加载器委托机制:当前的类加载器会先委托个父类,一直到BootStrap类,若父类找到要加载的类就加载该类,子类就不加载,若父类没有找到,则退回给子类加载,直到发起委托的类。若发起委托的类也没有找到,则抛出异常。

System 类是由BootStrap 加载的,因此通常情况下,自己写一个System类不会被虚拟机加载。但是可以自己写类加载器去加载自己写的类。
*/

/*26-45
 模板方法设计模式:


仅复写findClass,不用复写loadClass
 类加载器的原理:
	public Class findClass(String name){
		byte[] b = loadClassData(name);
		return defineClass(name,b,0,b.length);//把二进制数组转变成类字节码。
	}
*/

/*26-46

自定义类加载器
	protected Class<?> findClass(String name){
		String classFileName = classDir +"\\" +name +".class";
		try {
			FileInputStream fis = new FileInputStream(classFileName);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			cypher(fis,bos);
			fis.close();
			byte[] bytes = bos.toByteArray();
			return defineClass(bytes,0,bytes.length);
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		
		return super.findClass(name);
	}
*/


/*26-48
如果A用到了B,B就由A的加载器去加载

注意extends 是 子类的类加载器与父类的类加载器的关系。
*/

/*26-49
代理可以用来调试程序的运行时间

如果目标类没有实现接口,则可以使用CGLib库 来动态生成代理

代理的方法可以在目标方法的 前,后,及catch块中 增加代码

*/

//26-50_54
package cn.itcast.day3;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Collection;

public class ProxyTest {

	/**
	 * @param args
	 * @throws SecurityException 
	 * @throws NoSuchMethodException 
	 * @throws InvocationTargetException 
	 * @throws IllegalArgumentException 
	 * @throws IllegalAccessException 
	 * @throws InstantiationException 
	 */
	public static void main(String[] args) throws NoSuchMethodException, 
	SecurityException, InstantiationException, IllegalAccessException, 
	IllegalArgumentException, InvocationTargetException {
		// TODO Auto-generated method stub

		Class clazz = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
		System.out.println(clazz.getName());
		
		System.out.println("begin constructors______________________");
		Constructor[] cons = clazz.getConstructors();
		for(Constructor con : cons){
			String name = con.getName();
			System.out.println("con = " + con);
			System.out.println("conName = " +name);
			
			StringBuilder sb = new StringBuilder(name);
			sb.append("(");
			Class[] clazzParams = con.getParameterTypes();
			for(Class clazzParam : clazzParams){
				sb.append(clazzParam.getName()).append(",");
			}
			
			if(clazzParams != null && clazzParams.length !=0)
				sb.deleteCharAt(sb.length()-1);
			sb.append(")");
			System.out.println(sb);
		}
		
		
		System.out.println("begin methods______________________");
		Method[] methods = clazz.getMethods();
		for(Method method : methods){
			String name = method.getName();
			//System.out.println("method = " + method);
			System.out.println("methodName = " +name);
			
			/*StringBuilder sb = new StringBuilder(name);
			sb.append("(");
			Class[] clazzParams = method.getParameterTypes();
			for(Class clazzParam : clazzParams){
				sb.append(clazzParam.getName()).append(",");
			}
			
			if(clazzParams.length !=0)
				sb.deleteCharAt(sb.length()-1);
			sb.append(")");
			System.out.println(sb);*/
		}
		
		System.out.println("begin instance______________________");
		Constructor<Collection> con = clazz.getConstructor(InvocationHandler.class);
		Collection coll = con.newInstance(new InvocationHandler(){
			
			@Override
			public Object invoke(Object proxy, Method method, Object[] args)
					throws Throwable {
				// TODO Auto-generated method stub
				return null;
			}
			
		});
		
		coll.clear();
		//coll.size();//会出错,因为 proxy返回的null 与 size需求的返回的int 不相符。
		
		
		System.out.println("begin instance______________________");
		Collection collProxy = (Collection) Proxy.newProxyInstance(
				Collection.class.getClassLoader(), 
				new Class[]{Collection.class}, 
				new InvocationHandler() {
					Collection collTarget = new ArrayList();
					@Override
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						// TODO Auto-generated method stub
						long start = System.currentTimeMillis();
						
						Object retVal = method.invoke(collTarget, args);
						long end = System.currentTimeMillis();
						System.out.println("time cost: " + (end - start));
						return retVal;
					}
				});
		
		collProxy.add("this");
		collProxy.add("is");
		collProxy.add("proxy");
		System.out.println(collProxy.size());
		collProxy.clear();
		
		System.out.println("begin instance of framework______________________");
		final Collection collTarget = new ArrayList();
		Collection collProxy1 = (Collection) gerProxy(collTarget,new MyAdvice());
	}

	private static Object gerProxy(final Object target,final Advice advice) {
		Object proxy = Proxy.newProxyInstance(
				target.getClass().getClassLoader(), 
				new Class[]{target.getClass()}, 
				new InvocationHandler() {
					
					@Override
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						
						//long start = System.currentTimeMillis();
						advice.beforeMethod(method);
						
						Object retVal = method.invoke(target, args);
						
						advice.afterMethod(method);
						//long end = System.currentTimeMillis();
						
						return retVal;
					}
				});
		return proxy;
	}

}

class MyAdvice implements Advice{

	@Override
	public void beforeMethod(Method m) {
		// TODO Auto-generated method stub
		long start = System.currentTimeMillis();
	}

	@Override
	public void afterMethod(Method m) {
		// TODO Auto-generated method stub
		long end = System.currentTimeMillis();
		System.out.println("time cost: " + (end - start));
	}
	
}

//Advice
package cn.itcast.day3;

import java.lang.reflect.Method;

public interface Advice {

	long start = 0;
	public void beforeMethod(Method m);
	public void afterMethod(Method m);
	
}

//26-56

package cn.heima.aopframework;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import cn.itcast.day3.Advice;

public class BeanFactory {

	Properties prop = new Properties();
	
	public BeanFactory(InputStream ips){
		try {
			prop.load(ips);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Object getBean(String name){
		String className = prop.getProperty(name);
		Object bean = null;
		try {
			Class clazz = Class.forName(className);
			bean = clazz.newInstance();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		
		if (bean instanceof ProxyFactoryBean) {
			Object proxy = null;
			try {
				ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)bean;
				Advice advice = (Advice)Class.forName(prop.getProperty(name+".advice")).newInstance();
				Object target = Class.forName(prop.getProperty(name+ ".target")).newInstance();
				proxyFactoryBean.setAdvice(advice);
				proxyFactoryBean.setTarget(target);
				proxy = proxyFactoryBean.getProxy();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			return proxy;
		} else {

		}
		return bean;
	}
}


package cn.heima.aopframework;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import cn.itcast.day3.Advice;

public class ProxyFactoryBean {
	private Advice advice;
	private Object target;

	public Advice getAdvice() {
		return advice;
	}
	public void setAdvice(Advice advice) {
		this.advice = advice;
	}
	public Object getTarget() {
		return target;
	}
	public void setTarget(Object target) {
		this.target = target;
	}
	
	public Object getProxy(){
		Object proxy = Proxy.newProxyInstance(
				target.getClass().getClassLoader(), 
				new Class[]{target.getClass()}, 
				new InvocationHandler() {
					
					@Override
					public Object invoke(Object proxy, Method method, Object[] args)
							throws Throwable {
						
						//long start = System.currentTimeMillis();
						advice.beforeMethod(method);
						
						Object retVal = method.invoke(target, args);
						
						advice.afterMethod(method);
						//long end = System.currentTimeMillis();
						
						return retVal;
					}
				});
		return proxy;	
	}
}


package cn.heima.aopframework;

import java.io.InputStream;

public class ProxyTest {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		InputStream ips = ProxyTest.class.getResourceAsStream(config.prop);
		Object bean = new BeanFactory(ips).getBean("xxx");
		System.out.println(bean.getClass().getName());
	}

}


---------------------- ASP.Net+Android+IO开发S.Net培训、期待与您交流! ---------------------- 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值