---------------------- ASP.Net+Android+IOS开发、.Net培训、期待与您交流! ----------------------
对JavaBean的简单内省操作:
package cn.itcast.day1;
import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class IntroSpectorTest {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
ReflectTest rt = new ReflectTest(3,4);
String propertyName = "x";
methodGet(rt, propertyName);
int value = 7;
methodSet(rt, propertyName, value);
}
private static void methodSet(ReflectTest rt, String propertyName, int value)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd1 = new PropertyDescriptor(propertyName,rt.getClass());
Method methodSet = pd1.getWriteMethod();
methodSet.invoke(rt, value);
System.out.println(rt.getX());
}
private static void methodGet(ReflectTest rt, String propertyName)
throws IntrospectionException, IllegalAccessException,
InvocationTargetException {
PropertyDescriptor pd = new PropertyDescriptor(propertyName,rt.getClass());
Method methodGet = pd.getReadMethod();
Object obj = methodGet.invoke(rt);
System.out.println(obj);
}
}
package cn.itcast.day1;
public class ReflectTest {
private int x;
public int y ;
public String str1 ="ball";
public String str2= "basketball";
public String str3 ="itcast";
public ReflectTest(int x, int y) {
super();
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public String toString()
{
return str1+":"+str2+":"+str3;
}
}
注解
注解是Jdk1.5新特性。
加了注解相当于给程序添加标记,加了标记后javac编译器,开发工具和其他程序可以用反射来了解你的类及各种元素上有何种标记,就去干相应的事。标记可以加在包,类,成员变量,方法,方法的参数以及局部变量。注解相当于一个类,定义注解和定义接口相似,注解类,应用了注解类的类,调用应用了注解类的类。
常用的注解
@Deprecated方法过时
@Override覆盖
@SupperessWarnings压缩警告
@Retention作用时间
@Target作用目标
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
/*
* 注解
*/
@ItcastAnnotation(color="red",value="abc",annotationAttr=@MetaAnnotation("flx"),arr={3,5})
public class AnnotationTest
{
@SuppressWarnings("deprecation")//忽略警告
@ItcastAnnotation("xyz")//
public static void main(String[] args)throws Exception
{
if(Annotation.class.isAnnotationPresent(ItcastAnnotation.class))
{
ItcastAnnotation annotation=
(ItcastAnnotation)ItcastAnnotation.class.getAnnotation(ItcastAnnotation.class);//获得元素
System.out.println(annotation.color());//获取属性
System.out.println(annotation.value());
System.out.println(annotation.arr().length);
System.out.println(annotation.lamp().nextLamp().name());//获取枚举的下一个值
System.out.println(annotation.annotationAttr().value());//获取注释的值
}
Method mainMethod = ItcastAnnotation.class.getMethod("main", String[].class);
ItcastAnnotation annotation2=(ItcastAnnotation)mainMethod.getAnnotation(ItcastAnnotation.class);
System.out.println(annotation2.value());
}
}
类加载器
Java虚拟机中可以安装多个类加载器,系统默认三个主要类加载器,每个类负责加载特定位置的类:BootStrap,ExtClassLoader,AppClassLoader
类加载器也是Java类,因为其他是java类的类加载器本身也要被类加载器加载,显然必须有第一个类加载器不是不是java类,这正是BootStrap。
Java虚拟机中的所有类装载器采用具有父子关系的树形结构进行组织,在实例化每个类装载器对象时,需要为其指定一个父级类装载器对象或者默认采用系统类装载器为其父级类加载。
类加载器的委托机制
当Java虚拟机要加载一个类时,到底派出哪个类加载器去加载呢?
首先当前线程的类加载器去加载线程中的第一个类。
如果类A中引用了类B,Java虚拟机将使用加载类A的类装载器来加载类B。
还可以直接调用ClassLoader.loadClass()方法来指定某个类加载器去加载某个类。
每个类加载器加载类时,又先委托给其上级类加载器。
当所有祖宗类加载器没有加载到类,回到发起者类加载器,还加载不了,则抛ClassNotFoundException,不是再去找发起者类加载器的儿子,因为没有getChild方法,即使有,那有多个儿子,找哪一个呢?
对着类加载器的层次结构图和委托加载原理,解释先前将ClassLoaderTest输出成jre/lib/ext目录下的itcast.jar包中后,运行结果为ExtClassLoader的原因。
import java.util.Date;
/*
* 类加载器
*/
public class ClassLoaderTest
{
public static void main(String[] args)throws Exception
{
//获取ClassLoaderTest的类加载器名称
System.out.println(ClassLoaderTest.class.getClassLoader().getClass().getName());
//获取System的类加载器,其加载器为空。
System.out.println(System.class.getClassLoader());
//下面的例子能显示出类加载器的子父类关系
ClassLoader loader=ClassLoaderTest.class.getClassLoader();
while(loader!=null)
{
System.out.println(loader.getClass().getName());//多态形式
loader=loader.getParent();
}
System.out.println(loader);
System.out.println("===============");
Class clazz = new MyClassLoader("itcastlib").loadClass("ClassLoaderAttachment");
Date d=(Date)clazz.newInstance();
System.out.println(new ClassLoaderAttachment().getClass().getClassLoader().getClass().getName());
System.out.println(d.toString());
}
}
import java.util.Date;
public class ClassLoaderAttachment extends Date
{
public String toString()
{
return "hello date tostring";
}
}
//自定义类加载器
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class MyClassLoader extends ClassLoader//既是类加载器又是加密工具
{
public static void main(String[] args)throws Exception
{
//将需要转换的文件路径和转换后文件存储路径传递进来
String srcPath=args[0];
String destDir=args[1];
//关联要转换文件
FileInputStream fis=new FileInputStream(srcPath);
//从要转换的文件路径中取出文件的名称并且和要存储的路径进行组合
String destFileName=srcPath.substring(srcPath.lastIndexOf("\\")+1);
String destPath=destDir+"\\"+destFileName;
//关联要存储的路径名
FileOutputStream fos=new FileOutputStream(destPath);
System.out.println("zhuhanshu");
cypher(fis,fos);
fis.close();
fos.close();
}
//通过^运算符将class文件进行加密,由于是^运算符所以此方法同时也是解密方法
private static void cypher(InputStream ips,OutputStream ops)throws Exception
{
System.out.println("cast");
int b=0;
while((b=ips.read())!=-1)
{
ops.write(b^0xff);//^1111 1111 1111 1111(255)
}
}
private String classDir;//要加载类所在的路径名
public MyClassLoader()
{
}
public MyClassLoader(String classDir)
{
this.classDir=classDir;
}
@Override
protected Class<?> findClass(String name)throws ClassNotFoundException
//在指定路径找到class文件并解密,再转为class
{
System.out.println("find");
String classFileName = classDir+"\\"+name+".class";//要加载类的路径和名称
try
{
FileInputStream fis=new FileInputStream(classFileName);
ByteArrayOutputStream bos=new ByteArrayOutputStream();
cypher(fis,bos);//调用加密、解密方法
fis.close();
byte[] bytes=bos.toByteArray();
System.out.println("fanhui");
return defineClass(bytes,0,bytes.length);
}
catch (Exception e)
{
e.printStackTrace();
}
return null;//super.findClass(name);
}
}
代理
package cn.itcast.day2;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.*;
public class ProxyTest {
/**
* @param args
*/
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
System.out.println(clazzProxy1);
Constructor[] constructors = clazzProxy1.getConstructors();
for(Constructor constructor: constructors)
{
String name = constructor.getName();
StringBuilder sb = new StringBuilder(name);
sb.append('(');
Class[] clazzParams = constructor.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.toString());
}
Method[] methods = clazzProxy1.getMethods();
for(Method method: methods)
{
String name = method.getName();
StringBuilder sb = new StringBuilder(name);
sb.append('(');
Class[] clazzParams = method.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.toString());
}
System.out.println("-----------------------------------------------");
Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
Collection proxy1 = (Collection)constructor.newInstance(new InvocationHandler(){
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
// TODO Auto-generated method stub
return null;
}});
System.out.println(proxy1);
final ArrayList target = new ArrayList();
Collection proxy2 =(Collection)getProxy(target,new MyAdvice());
proxy2.add("xxx");
proxy2.add("yyy");
proxy2.add("zzz");
System.out.println(proxy2.size());
}
private static Object getProxy(final Object target,final Advice advice) {
Object proxy2 = Proxy.newProxyInstance(
target.getClass().getClassLoader(),
target.getClass().getInterfaces(),
new InvocationHandler(){
public Object invoke(Object proxy, Method method,
Object[] args) throws Throwable {
advice.beforeMethod(method);
Object Value = method.invoke(target, args);
advice.afterMethod(method);
return Value;
}});
return proxy2;
}
}
package cn.itcast.day2;
import java.lang.reflect.Method;
public interface Advice {
void beforeMethod(Method method);
void afterMethod(Method method);
}
package cn.itcast.day2;
import java.lang.reflect.Method;
public class MyAdvice implements Advice {
long beginTime = 0;
public void beforeMethod(Method method) {
// TODO Auto-generated method stub
beginTime = System.currentTimeMillis();
}
public void afterMethod(Method method) {
// TODO Auto-generated method stub
long endTime = System.currentTimeMillis();
System.out.println(method.getName()+"::run time"+(endTime-beginTime));
}
}