Java-001-枚舉、反射古话、類加載器雏吭、內(nèi)省、注解陪踩、泛型杖们、代理

Java基礎(chǔ)總結(jié)

以下筆記整理自張孝祥老師的《Java高新技術(shù)》視頻教程

01 枚舉

public class EnumTest {
    public static void main(String[] args) {
        WeekDay weekDay2 = WeekDay.FRI;
        System.out.println(weekDay2);
        System.out.println(weekDay2.name());
        System.out.println(weekDay2.ordinal());    //排序從零開始
        System.out.println(WeekDay.valueOf("SUN").toString());
        System.out.println(WeekDay.values().length);
        
        new Date(300){//覆寫父類方法};
    }

    public enum WeekDay{
        SUN(1),MON(),TUE,WED,THI,FRI,SAT;
        private WeekDay(){System.out.println("first");}
        private WeekDay(int day){System.out.println("second");}
    }
    
    public enum TrafficLamp{
        //每個成員都是TrafficLamp的對象
        RED(30){//子類對象,調(diào)用有參構(gòu)造方法肩狂,覆寫父類方法
            public  TrafficLamp nextLamp(){
                return GREEN;
            }
        },
        GREEN(45){
            public  TrafficLamp nextLamp(){
                return YELLOW;
            }            
        },
        YELLOW(5){
            public  TrafficLamp nextLamp(){
                return RED;
            }            
        };
        public abstract TrafficLamp nextLamp();
        private int time;
        private TrafficLamp(int time){this.time = time;}
    }
}

02 反射

反射就是把Java類中的各種成分映射成相應的Java類

注意:反射Constructor摘完、Field:

  1. ∵方法和屬性都是對象的,∴要得到屬性值傻谁、更改屬性值孝治、調(diào)用用方法是要傳入具體的對象
  2. 調(diào)用靜態(tài)方法時對象傳入null即可

反射獲取泛型參數(shù)類型

public class GenericTest {
    public static void main(String[] args) throws Exception {
        ...
        //Vector<Date> v1 = new Vector<Date>();
        Method applyMethod = GenericTest.class.getMethod("applyVector", Vector.class);
        Type[] types = applyMethod.getGenericParameterTypes();    //以泛型方式得到每個參數(shù)的類型
        ParameterizedType pType = (ParameterizedType)types[0];    //第一個參數(shù)的類型
        System.out.println(pType.getRawType());                    //原始類型 :Vector
        System.out.println(pType.getActualTypeArguments()[0]);    //實際類型參數(shù):Date
    }
    
    public static void applyVector(Vector<Date> v1){        
    }
}

獲取父類泛型的實際參數(shù)類型

public abstract class DaoSupportImpl<T> implements DaoSupport<T> {
    private Class<T> clazz;
    public DaoSupportImpl() {
        // 得到T的真實類型
        // this表示當前new的對象實例.
        // getGenericSuperclass()表示獲取對象的泛型的父類的類型信息;即DaoSupport<T>
        ParameterizedType pt = (ParameterizedType) this.getClass().getGenericSuperclass();
        this.clazz = (Class) pt.getActualTypeArguments()[0]; // 獲取真實類型信息
        System.out.println("-----> clazz = " + clazz);
    }
}

得到類的字節(jié)碼對象 Class

注意:
用類來得到Class审磁,用.class
用對象來得到Class谈飒,用getClass()方法
用完整類名來得到Class,用Class.forName(“...”);

Person p = new Person();

  1. Class c1 = Person.class [1]
  2. Class c2 = p.getClass() //用對象來得到Class
  3. Class c3 = Class.forName(“com.ttino.model.Person”);
  4. Android中的方法态蒂,僅參考
private void getCacheSize(PackageInfo packageInfo) {
    try {
        Class<?> clazz = getClassLoader().loadClass("packageManager");
        //通過反射獲取到當前的方法
        Method method = clazz.getDeclaredMethod("getPackageSizeInfo", 
                            String.class,IPackageStatsObserver.class);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

有9個預定義的Class對象 :8個基本類型 + void (void.class)
**int.class.isPrimitive(); ** //true杭措;是否是原始(基本)類型 的字節(jié)碼
**int[].class.isArray(); ** //true; 判斷Class是否是數(shù)組

java四類八種基本數(shù)據(jù)類型:

第一類:整型 byte short int long
第二類:浮點型 float double
第三類:邏輯型 boolean(它只有兩個值可取true false)
第四類:字符型 char

反射構(gòu)造方法Constructor

反射字段Filed

/**
 * 將一個對象中的所有String類型的成員變量所對應的字符串內(nèi)容中的"b"改成"a"
 */
Object obj = Class.forName("...").newInstance();
Field[] fields = obj.getClass().getDeclaredFields();
for(Field f : fields){
    if(f.getType() == String.class){ //字節(jié)碼用==來比較,因為只有一份
        f.setAccessible(true);
        String newValue = ((String)f.get(obj)).replace('b', 'a');
        f.set(obj, newValue);    
    }
}
System.out.println(obj);//覆寫了obj的toString()方法

反射方法Method

//兼容jdk1.4钾恢,在1.5中的寫法
//方法一:讓1.5編譯器去拆手素,拆除來的就是Object
//mainMethod.invoke(null, new Object[]{new String[]{"111","222","333"}});
//方法二:告訴1.5的編譯器不要拆
mainMethod.invoke(null, (Object)new String[]{"111","222","333"});

數(shù)組反射

維度和類型都相同的數(shù)組,class是同一種類型

數(shù)組和Object的對應關(guān)系:

int [] a1 = new int[]{1,2,3};
int [] a2 = new int[4];
int[][] a3 = new int[2][3];
String [] a4 = new String[]{"a","b","c"};

Object aObj1 = a1;
Object aObj2 = a4;
//Object[] aObj3 = a1;//a1數(shù)組里裝的是int, int(基本類型)不是Object, Integer(對象包裝類)是
Object[] aObj4 = a3;//數(shù)組里裝的是數(shù)組瘩蚪,數(shù)組的父類是Object[a1.getClass().getSuperclass().getName()]
Object[] aObj5 = a4;//數(shù)組里裝的是String泉懦,String是Object

打印數(shù)組里的內(nèi)容:
//整數(shù)不會轉(zhuǎn)為List中的元素
System.out.println(Arrays.asList(a1));//[[I@4e25154f]
System.out.println(Arrays.asList(a4));//[a, b, c] //String轉(zhuǎn)了

asList(T...a) //1.5 // List<String> stooges = 
                        Arrays.asList("Larry", "Moe", "Curly");
asList(Object[] o)//1.4

反射數(shù)組的長度和內(nèi)容,用Array類

private static void printObject(Object obj) {
    Class clazz = obj.getClass();
    if(clazz.isArray()){
        int len = Array.getLength(obj);//長度
        for(int i=0;i<len;i++){
            System.out.println(Array.get(obj, i));//內(nèi)容
        }
    }else{//如果不是數(shù)組疹瘦,直接打印
        System.out.println(obj);
    }    
}

03 框架與工具類

  1. 開發(fā)商賣給你房子崩哩,你裝上自己的門,買了把鎖

框架:開發(fā)商提供的房子拱礁,可以賣給任何人
自己的類:門看成是自己的做的琢锋,用戶將門裝在房子中
工具類:鎖看成是買的別人的,鎖被門調(diào)用

  1. 框架調(diào)用用戶提供的類呢灶,工具類被用戶調(diào)用

04 類加載器

  1. 最直接的方式
InputStream ips = new FileInputStream("config.properties");
  1. 用Class得到類加載器getClassLoader().getResourceAsStream吴超。默認從classpath(編譯好的.class文件的存放路徑)根目錄下查找文件
    注意:路徑前面不加/
InputStream ips = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");
  1. 直接用Class的getResourceAsStream()
  • 3.1、如果不用/開頭鸯乃,默認從ReflectTest2.class所在目錄下開始查找 [相對路徑]
InputStream ips = ReflectTest2.class.getResourceAsStream("config.properties");
  • 3.2鲸阻、如果用/開頭跋涣,絕對路徑查找
InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resources/config.properties");

4.示例

InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resources/config.properties");
Properties props = new Properties();
props.load(ips);
//這里釋放的是對象關(guān)聯(lián)的系統(tǒng)資源,不是對象本省,ips對象由JVM管理
ips.close();//釋放對象關(guān)聯(lián)的系統(tǒng)資源鸟悴,否則會有內(nèi)存泄露
String className = props.getProperty("className");
Collection collections = (Collection)Class.forName(className).newInstance();

05 內(nèi)省(Introspector)操作JavaBean

//ReflectPoint pt1 = new ReflectPoint(3,5); //JavaBean    
//String propertyName = "x";
//getProperty(pt1, propertyName);

private static Object getProperty(Object pt1, String propertyName)throws Exception {
    /*
    //方式一
PropertyDescriptor pd = new PropertyDescriptor(propertyName, pt1.getClass());//傳入屬性名和Class
    Method methodGetX = pd.getReadMethod();
    Object retVal = methodGetX.invoke(pt1);
*/
    
    //方式二
    BeanInfo beanInfo =  Introspector.getBeanInfo(pt1.getClass());
    PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
    Object retVal = null;
    for(PropertyDescriptor pd : pds){
        if(pd.getName().equals(propertyName)) {
            Method methodGetX = pd.getReadMethod();
            retVal = methodGetX.invoke(pt1);
            break;
        }
    }
    return retVal;
}

06 BeanUtils操作JavaBean

copyProperties():將一個對象的屬性復制到另一對象
descirble():將JavaBean轉(zhuǎn)為map
populate():將map的內(nèi)容填充到JavaBean

ReflectPoint pt1 = new ReflectPoint(3,5);
//BeanUtils set時會以String類型來set陈辱;get時會以String類型來返回
//參數(shù):對象、屬性名
BeanUtils.getProperty(pt1, "x").getClass().getName();//java.lang.String细诸;實際上x是int型
//參數(shù):隊形沛贪、屬性名,值
BeanUtils.setProperty(pt1, "x", "9");
/*
//java7的新特性
Map map = {name:"zxx",age:18};
BeanUtils.setProperty(map, "name", "lhm");
*/
//級聯(lián)屬性
BeanUtils.setProperty(pt1, "birthday.time", "111");
System.out.println(BeanUtils.getProperty(pt1, "birthday.time"));

//PropertyUtils操作JavaBean        
//操作時震贵,注意類型要與屬性字段的類型對應
PropertyUtils.setProperty(pt1, "x", 9);
System.out.println(PropertyUtils.getProperty(pt1, "x").getClass().getName());//java.lang.Integer

07 注解

@SuppressWarnings(“deprecation”):取消警告 //source階段利赋,編譯器用完了(編譯成.class)就沒用了
@Deprcation:過時 //runtime階段,編譯器是通過讀類二進制來檢查某個方法是否過期
@Override:覆寫 //source階段

注解應用:3個類
注解類 + 應用了“注解類”的類 + 對‘應用了“注解類”的類’進行反射操作的類

//SOURCE猩系、CLASS媚送、RUNTIME分別對應的注解生命周期:java源文件?class文件?內(nèi)存中的字節(jié)碼。默認CLASS
@Retention(RententionPolicy.RUNTIME)//保留到運行期間[元注解]寇甸;或(value=”RUNTIME”)
//@Target({ElementType.METHOD,ElementType.TYPE}) //只能放在方法和類型上
public @interface ItcastAnnotation    {}

元注解:為注解服務的注解
元數(shù)據(jù):數(shù)據(jù)的數(shù)據(jù)
原信息:信息的信息

注解類:

EnumTest類參考枚舉
ItcastAnnotaion.java

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.TYPE})
public @interface ItcastAnnotation {
    String color() default "blue";
    String value();
    int[] arrayAttr() default {3,4,4};
    EnumTest.TrafficLamp lamp() default EnumTest.TrafficLamp.RED;
    MetaAnnotation annotationAttr() default @MetaAnnotation("lhm");
}

MetaAnnotaion.java
public @interface MetaAnnotation {
    String value();
}

應用了“注解類”的類塘偎,其中Main方法暫作為“對注解進行解析”的代碼存放處

@ItcastAnnotation(annotationAttr=@MetaAnnotation("flx"),color="red",value="abc",arrayAttr=1)
public class AnnotationTest {
    @SuppressWarnings("deprecation")
    @ItcastAnnotation("xyz")
    public static void main(String[] args) throws Exception{
         System.runFinalizersOnExit(true);//測試@suppressWarnings注解
         //如果AnnotionTest類上存在ItcastAnnotation注解
        if(AnnotationTest.class.isAnnotationPresent(ItcastAnnotation.class)){
            ItcastAnnotation annotation = (ItcastAnnotation)AnnotationTest.class.getAnnotation(ItcastAnnotation.class);
            System.out.println(annotation.color());//red
            System.out.println(annotation.value());//abc
            System.out.println(annotation.arrayAttr().length);//1
            System.out.println(annotation.lamp().nextLamp().name());//GREEN
            System.out.println(annotation.annotationAttr().value());//flx
        }

        //獲取Main方法上的注解
        Method mainMethod = AnnotationTest.class.getMethod("main", String[].class);
        ItcastAnnotation annotation2 = (ItcastAnnotation)mainMethod.getAnnotation(ItcastAnnotation.class);
        System.out.println(annotation2.value());//xyz
    }
}

08 泛型

泛型是給編譯器看的,編譯完后不保存泛型的類型

  1. 整個ArrayList<E> 稱為泛型類型
  2. ArrayList<E>中的E 稱為類型變量或類型參數(shù)
  3. 整個ArrayList<Integer> 稱為參數(shù)化的類型
  4. ArrayList<Integer>中的Integer 稱為類型參數(shù)的實例或?qū)嶋H類型參數(shù)
  5. ArrayList<Integer>中的<> 念typeof
  6. ArrayList 稱為原始類型

泛型中的通配符:
?:任意類型

自定義泛型:

1 方法:

1.1拿霉、自定義類型T要在返回類型前吟秩、緊挨著返回類型聲明
1.2、返回類型T推斷:取最小公倍數(shù)友浸;如果有返回類型峰尝,優(yōu)先考慮返回類型

copy(new Date[], new String[10]);
<T> void copy(T dest, T[] src){} 

類型推斷有時要考慮<>中的類型傳遞:

copy(new Vector<String>[], new String[10]);//copy(new Vector<Date>[], new String[10]):錯誤
<T> void copy(Collection<T> col, T[] arr){} 

1.3、泛型T的實際類型只能是引用類型收恢,不能是基本數(shù)據(jù)類型

private static <T> T add<T x, T y){
    return null;
}

限定T

private static <T extends Serializable&Number> T sub(Class<T> clazz){}

泛型異常

private static <T extends Exception > void Say() throws T{
    try{}catch(Exception e){throw (T)e}
}

2.類

dao:data access object,數(shù)據(jù)訪問對象
類里面的靜態(tài)成員不能使用泛型對象

public class GenericDao<T>{
}

09 類加載器

  • BootStrap:jre/lib/rt.jar
    • |-ExtClassLoader:jre/lib/ext/*.jar
      • |-AppClassLoader:classpath下指定的所有jar或目錄
        • |-MyClassLoader:自定義的特殊目錄

Thread指定類加載器:
ClassLoader getContextClassLoader() 返回該線程的上下文 ClassLoader
void setContextClassLoader(ClassLoader cl) 設置該線程的上下文 ClassLoader

自定義的類加載器加載指定的類:
ClassLoader.loadClass()

類加載器委托加載機制:
父加載器加載 -> 子加載器加載

自定義類加載器

原始類:

public class ClassLoaderAttachment extends Date {
    public String toString(){
        return "hello,itcast";
    } 
}

調(diào)用類:

public static void main(String[] args) throws Exception {
    //加載.class文件
    Class clazz = new MyClassLoader("itcastlib").loadClass("cn.itcast.day2.ClassLoaderAttachment");
    Date d1 =  (Date)clazz.newInstance();
    System.out.println(d1);
}

加載器:

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);
        cypher(fis,fos);
        fis.close();
        fos.close();
    }
    //加密方法
    private static void cypher(InputStream ips ,OutputStream ops) throws Exception{
        int b = -1;
        while((b=ips.read())!=-1){
            ops.write(b ^ 0xff);
        }
    }

//-------------------功能分割線------------------------
    //class文件的目錄
    private String classDir;

    //查找Class
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        //文件全名 = 目錄 + \ + 名稱 + .class
        String classFileName = classDir + "\\"  + name.substring(name.lastIndexOf('.')+1) + ".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) {
            e.printStackTrace();
        }
        return null;
    }
    
    public MyClassLoader(){
    }
    public MyClassLoader(String classDir){
        this.classDir = classDir;
    }
}

10 代理的概念與作用

JVM代理
三個參數(shù):1祭往、類加載器伦意;2、接口硼补;3驮肉、InvocationHandler

Proxy生成的代理類繼承了Object的方法:
其中只有hashCode、equals已骇、toString三個方法才交給invocationHandler的invoke去處理离钝,其它方法都有自己的實現(xiàn)

1、分步獲取

獲取代理類 -> 獲取代理類的構(gòu)造方法 -> 構(gòu)造方法中傳入InvocationHandler來創(chuàng)建實例對象

public class ProxyTest {
    public static void main(String[] args) throws Exception{
        //0褪储、創(chuàng)建Collection接口的代理類
        //參數(shù)1:類加載器卵渴;參數(shù)2:接口
        Class clazzProxy1 = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
        //1、打印代理類的名稱
        System.out.println(clazzProxy1.getName());
        
        //2鲤竹、獲取代理類的所有構(gòu)造方法
        System.out.println("----------begin constructors list----------");
        Constructor[] constructors = clazzProxy1.getConstructors();
        for(Constructor constructor : constructors){
            String name = constructor.getName();
            StringBuilder sBuilder = new StringBuilder(name);
            sBuilder.append('(');
            Class[] clazzParams = constructor.getParameterTypes();
            for(Class clazzParam : clazzParams){
                sBuilder.append(clazzParam.getName()).append(',');
            }
            if(clazzParams!=null && clazzParams.length != 0)
                sBuilder.deleteCharAt(sBuilder.length()-1);
            sBuilder.append(')');
            System.out.println(sBuilder.toString());            
        }

        //3浪读、獲取代理類的所有方法
        System.out.println("----------begin methods list----------");
        Method[] methods = clazzProxy1.getMethods();
        for(Method method : methods){
            String name = method.getName();
            StringBuilder sBuilder = new StringBuilder(name);
            sBuilder.append('(');
            Class[] clazzParams = method.getParameterTypes();
            for(Class clazzParam : clazzParams){
                sBuilder.append(clazzParam.getName()).append(',');
            }
            if(clazzParams!=null && clazzParams.length != 0)
                sBuilder.deleteCharAt(sBuilder.length()-1);
            sBuilder.append(')');
            System.out.println(sBuilder.toString());            
        }
        
        //4、創(chuàng)建代理類的實例
        System.out.println("----------begin create instance object----------");
        //Object obj = clazzProxy1.newInstance();//錯誤,代理類中沒有不帶參數(shù)的構(gòu)造方法
        //4.1碘橘、獲取唯一的構(gòu)造方法
        Constructor constructor = clazzProxy1.getConstructor(InvocationHandler.class);
        
        //自定義InvocationHandler類
        class MyInvocationHander1 implements InvocationHandler{
            //參數(shù)1:代理對象互订、參數(shù)2:代理對象的某個方法、參數(shù)3:方法接受的參數(shù)
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        }
        Collection proxy1 = (Collection)constructor.newInstance(new MyInvocationHander1());
        System.out.println(proxy1.toString());
        proxy1.clear();
        //proxy1.size(); //invoke返回null痘拆,size()要的是整數(shù)仰禽,null不能轉(zhuǎn)成整數(shù),所以報錯

        Collection proxy2 = (Collection)constructor.newInstance(new InvocationHandler(){
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });
    }
}

2纺蛆、一步到位

Collection proxy3 = (Collection) Proxy.newProxyInstance(
        Collection.class.getClassLoader(),    // 參數(shù)1:ClassLoader
        new Class[] { Collection.class },    // 參數(shù)2:Class[]
        new InvocationHandler() {             // 參數(shù)3:InvocationHandler
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                ArrayList target = new ArrayList();
                 return method.invoke(target, args);
            }
});

proxy3.add("111"); Syso(proxy3.size());//0
//原因:每調(diào)用一次方法都會去調(diào)用InvocationHandler的invoke方法坟瓢,而每一次都會new一個ArrayList
//可以把ArrayList改成InvoketionHandler的成員變量

3、AOP原理

public class ProxyTest {
    public static void main(String[] args) throws Exception{
        final ArrayList target = new ArrayList();            
        Collection proxy3 = (Collection)getProxy(target,new MyAdvice());
        proxy3.add("zxx");
        proxy3.add("lhm");
        proxy3.add("bxd");
        System.out.println(proxy3.size());
        System.out.println(proxy3.getClass().getName());
    }

    private static Object getProxy(final Object target,final Advice advice) {
        Object proxy3 = 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 retVal = method.invoke(target, args);
                        advice.afterMethod(method);
                        return retVal;                                                
                    }
                });
        return proxy3;
    }
}



public class MyAdvice implements Advice {
    long beginTime = 0;
    public void afterMethod(Method method) {
        System.out.println("從傳智播客畢業(yè)上班啦犹撒!");        
        long endTime = System.currentTimeMillis();
        System.out.println(method.getName() + " running time of " + (endTime - beginTime));

    }

    public void beforeMethod(Method method) {
        System.out.println("到傳智播客來學習啦折联!");
        beginTime = System.currentTimeMillis();
    }
}



public interface Advice {
    void beforeMethod(Method method);
    void afterMethod(Method method);
}

4、Spring的Bean工廠模擬

1识颊、BeanFactory.java

public class BeanFactory {
    //加載配置文件
    Properties props = new Properties();
    public BeanFactory(InputStream ips){
        try {
            props.load(ips);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    //創(chuàng)建Bean
    public Object getBean(String name){//傳入name诚镰,對象配置文件的xxx
        String className = props.getProperty(name);
        Object bean = null;
        try {//創(chuàng)建JavaBean
            Class clazz = Class.forName(className);
            bean = clazz.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        } 
        
        //如果bean是ProxyFactoryBean,創(chuàng)建代理對象
        if(bean instanceof ProxyFactoryBean){
            Object proxy = null;
            //由ProxyFactoryBean來創(chuàng)建代理對象
            ProxyFactoryBean proxyFactoryBean = (ProxyFactoryBean)bean;
            try {
                Advice advice = (Advice)Class.forName(props.getProperty(name + ".advice")).newInstance();
                Object target = Class.forName(props.getProperty(name + ".target")).newInstance();
                proxyFactoryBean.setAdvice(advice);
                proxyFactoryBean.setTarget(target);
                proxy = proxyFactoryBean.getProxy();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return proxy;
        }
        return bean;
    }
}

2祥款、ProxyFactoryBean.java

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

    ... get和set方法

    public Object getProxy() {
        Object proxy3 = Proxy.newProxyInstance(
                target.getClass().getClassLoader(),
                /*new Class[]{Collection.class},*/
                target.getClass().getInterfaces(),
                new InvocationHandler(){
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        advice.beforeMethod(method);
                        Object retVal = method.invoke(target, args);
                        advice.afterMethod(method);
                        return retVal;                        
                    }
                });
        return proxy3;
    }
}

3清笨、config.properties

#xxx=java.util.ArrayList
xxx=cn.itcast.day3.aopframework.ProxyFactoryBean
xxx.advice=cn.itcast.day3.MyAdvice
xxx.target=java.util.ArrayList

4、測試類:

public class AopFrameworkTest {
    public static void main(String[] args) throws Exception {
        InputStream ips = AopFrameworkTest.class.getResourceAsStream("config.properties");
        Object bean = new BeanFactory(ips).getBean("xxx");
        System.out.println(bean.getClass().getName());
        ((Collection)bean).clear();
    }
}

  1. 作用:返回字節(jié)碼對象刃跛。如果字節(jié)碼之前被加載過抠艾,已存在JVM中,則直接返回...桨昙;如果沒有检号,則先用類加載器加載,將加載的字節(jié)碼保存到JVM中蛙酪,然后返回... ?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末齐苛,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子桂塞,更是在濱河造成了極大的恐慌凹蜂,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件阁危,死亡現(xiàn)場離奇詭異玛痊,居然都是意外死亡,警方通過查閱死者的電腦和手機狂打,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評論 3 394
  • 文/潘曉璐 我一進店門擂煞,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人菱父,你說我怎么就攤上這事颈娜〗L樱” “怎么了?”我有些...
    開封第一講書人閱讀 163,912評論 0 354
  • 文/不壞的土叔 我叫張陵官辽,是天一觀的道長蛹磺。 經(jīng)常有香客問我,道長同仆,這世上最難降的妖魔是什么萤捆? 我笑而不...
    開封第一講書人閱讀 58,449評論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮俗批,結(jié)果婚禮上俗或,老公的妹妹穿的比我還像新娘。我一直安慰自己岁忘,他們只是感情好辛慰,可當我...
    茶點故事閱讀 67,500評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著干像,像睡著了一般帅腌。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上麻汰,一...
    開封第一講書人閱讀 51,370評論 1 302
  • 那天速客,我揣著相機與錄音,去河邊找鬼五鲫。 笑死溺职,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的位喂。 我是一名探鬼主播浪耘,決...
    沈念sama閱讀 40,193評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼忆某!你這毒婦竟也來了点待?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,074評論 0 276
  • 序言:老撾萬榮一對情侶失蹤弃舒,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后状原,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體聋呢,經(jīng)...
    沈念sama閱讀 45,505評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,722評論 3 335
  • 正文 我和宋清朗相戀三年颠区,在試婚紗的時候發(fā)現(xiàn)自己被綠了削锰。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,841評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡毕莱,死狀恐怖器贩,靈堂內(nèi)的尸體忽然破棺而出颅夺,到底是詐尸還是另有隱情,我是刑警寧澤蛹稍,帶...
    沈念sama閱讀 35,569評論 5 345
  • 正文 年R本政府宣布吧黄,位于F島的核電站,受9級特大地震影響唆姐,放射性物質(zhì)發(fā)生泄漏拗慨。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,168評論 3 328
  • 文/蒙蒙 一奉芦、第九天 我趴在偏房一處隱蔽的房頂上張望赵抢。 院中可真熱鬧,春花似錦声功、人聲如沸烦却。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,783評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽其爵。三九已至,卻和暖如春筹裕,著一層夾襖步出監(jiān)牢的瞬間醋闭,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,918評論 1 269
  • 我被黑心中介騙來泰國打工朝卒, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留证逻,地道東北人。 一個月前我還...
    沈念sama閱讀 47,962評論 2 370
  • 正文 我出身青樓抗斤,卻偏偏與公主長得像囚企,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子瑞眼,可洞房花燭夜當晚...
    茶點故事閱讀 44,781評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 在經(jīng)過一次沒有準備的面試后龙宏,發(fā)現(xiàn)自己雖然寫了兩年的android代碼,基礎(chǔ)知識卻忘的差不多了伤疙。這是程序員的大忌银酗,沒...
    猿來如癡閱讀 2,841評論 3 10
  • 整體Retrofit內(nèi)容如下: 1、Retrofit解析1之前哨站——理解RESTful 2徒像、Retrofit解析...
    隔壁老李頭閱讀 4,577評論 2 12
  • 紅衛(wèi)小學小叮當教育五年級黃語妍 一天黍特,我正寫作文,我把筆拿在手中旋轉(zhuǎn)锯蛀,想不出要寫什么灭衷,就在這時筆掉在了地...
    佳韻作文向老師閱讀 226評論 0 0
  • 那天下午我們在庫房練琴,和往常一樣討論琴技旁涤、吃東西翔曲,神侃迫像。不知是誰把話題扯到大學無聊的生活來,大家都有感而發(fā)瞳遍,氣氛...
    讀破書萬卷閱讀 185評論 0 0
  • 在與朋友們的閑聊中,他們總是不會忘記對你表達一番真誠地艷羨份蝴,說犁功,作為老師真幸福,馬上有漫長的兩個月的暑假等著你婚夫,想...
    坐忘mao閱讀 279評論 0 0