Java学习

黑马程序员-Java高新技术

2015-06-12  本文已影响558人  狼孩

-------android培训java培训期待与您交流!----------

静态导入
package com.sergio.NewTecl;
//静态导入包中的所有静态方法
import static java.lang.Math.*;
//静态导入包中某个静态方法
//import static java.lang.Math.max;
/**
 * 静态导入例子
 * Created by Sergio on 2015-06-03.
 */
public class ImportStatic {
    public static void main(String[] args) {
        System.out.println(max(3, 7));//求租嗲之
        System.out.println(abs(4 - 3));//求绝对值
    }
}
可变参数
package com.sergio.NewTecl;

/**
 * 可变参数
 * Created by Sergio on 2015-06-03.
 */
public class VariableParam {
    public static void main(String[] args) {
        System.out.println(add(3, 6));
        System.out.println(add(3, 1, 93, 23));
    }

    public static int add(int x, int... args) {
        int sum = 0;
        for (int i = 0; i < args.length; i++) {
            sum += args[i];
        }
        return sum;
    }
}
foreach
package com.sergio.NewTecl;

/**
 * foreach
 * Created by Sergio on 2015-06-03.
 */
public class ForEach {
    public static void main(String[] args) {
        int[] buf = new int[] {3, 5, 6, 4, 2, 8};
        int sums = 0;
        for (int sum : buf) {
            sums += sum;
        }
        System.out.println(sums);
    }
}
自动装箱拆箱
基本数据类型 引用数据类型
byte Byte
short Short
int Integer
long Long
boolean Boolean
float Float
double Double
char Character
package com.sergio.NewTecl;

/**
 * 装箱与拆箱
 * Created by Sergio on 2015-06-03.
 */
public class AutoBox {
    public static void main(String[] args) {
        Integer i = 2;//装箱
        Integer i2 = 4;
        System.out.println(i + i2);//拆箱

        Integer i3 = 12;
        Integer i4 = 12;
        //在int范围内,i3和i4对象引用的值相等
        System.out.println(i3 == i4);
        Integer i5 = 138;
        Integer i6 = 138;
        //超出了int范围,i5和i6的引用值不相等。
        System.out.println(i5 == i6);
    }
}
枚举
package com.sergio.NewTecl;

/**
 * 枚举应用示例
 * Created by Sergio on 2015-06-04.
 */
public class EnumTest1 {
    public static void main(String[] args) {
        WeekDay weekDay = WeekDay.FRI;
        System.out.println(weekDay.name());//枚举对象的名字
        System.out.println(weekDay.ordinal());//排列位置,从0开始
        System.out.println(WeekDay.valueOf("SUN"));//将字符串转成枚举对象
        System.out.println(WeekDay.values());//获得枚举元素的转化成数组
    }

    public enum WeekDay {
        SUN, MON, TUE, WED, THI, FRI, SAT
    }
}
    public enum WeekDay {
        SUN(2), MON(), TUE, WED, THI, FRI, SAT;//枚举的元素相当于枚举类型的对象,
                                               // 初始化时可以按照参数构造方法带入
        //空构造方法
        private WeekDay() {
            System.out.println("first");
        }

        //带参数构造方法
        private WeekDay(int day) {
            System.out.println("second");
        }
    }
    public enum TrafficLamp {
        //子类对象带参构造方法
        RED (30){
            public TrafficLamp nextLamp() {
                return GREEN;
            }
        },
        GREEN (45){
            public TrafficLamp nextLamp() {
                return YELLOW;
            }
        },
        YELLOW (5){
            public TrafficLamp nextLamp() {
                return RED;
            }
        };
        //枚举的抽象方法,需要枚举的元素即子类对象来实现
        public abstract TrafficLamp nextLamp();
        private long time;
        //枚举元素子类对象的构造方法
        private TrafficLamp(long time){
            this.time = time;
        }
    }
内省与JavaBean
package com.sergio.NewTecl;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * 内省的操作
 * Created by Sergio on 2015-06-08.
 */
public class JavaBeanDemo1 {
    public static void main(String[] args) throws Exception {
        JavaBeanTest jbt = new JavaBeanTest(3, 5);
        //要获取的JavaBean属性X
        String propertyName = "x";
        //获取JavaBean信息,get
        PropertyDescriptor pd = new PropertyDescriptor(propertyName, jbt.getClass());
        Method methodGetX = pd.getReadMethod();
        Object objValue = methodGetX.invoke(jbt);
        System.out.println(objValue);
        //set
        Object value = 4;
        Method methodSetX = pd.getWriteMethod();
        methodGetX.invoke(jbt, value);

        System.out.println(jbt.getX());
    }
}


class JavaBeanTest {
    private int x;
    public int y;

    JavaBeanTest(int x, int y) {
        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;
    }
}
BeanUtils
        //BeanUtils主要操作的值为字符串
        BeanUtils.getProperty(jbt, "x");
        BeanUtils.setProperty(jbt, "x", "9");
        //Map与BeanUtils的互操作。BeanUtils为值对象,而Map为键值对
        Map<String, Integer> map = new HashMap<String, Integer>();

        BeanUtils.setProperty(map, "name", "lisi");
        //PropertyUtils操作的本身的数据类型
        PropertyUtils.setProperty(jbt, "x", 9);
注解
package com.sergio.NewTecl;

/**
 * 注解定义
 * Created by Sergio on 2015-06-09.
 */
public @interface MetaAnnotation {
    String value();
}


============================
package com.sergio.NewTecl;

/**
 * 注解定义
 * Created by Sergio on 2015-06-09.
 */
public @interface MetaAnnotation {
    String value();
}


=====================
package com.sergio.NewTecl;

/**
 * 注解与反射
 * Created by Sergio on 2015-06-09.
 */

@AnnotationDemo(annotationAttr = @MetaAnnotation("hz"), color = "red", value = "12", arrayAttr = {2, 3, 4})
public class AnnotationTest {
    //阻止编译器过时API警告
    @SuppressWarnings("deprecation")
    @AnnotationDemo(value = "23")//此注解color已经有了默认值,只需设置value即可
    public static void main(String[] args) {
        System.runFinalizersOnExit(true);//过期API

        if (AnnotationTest.class.isAnnotationPresent(AnnotationDemo.class)) {
            AnnotationDemo annotation =
                (AnnotationDemo) AnnotationTest.class.getAnnotation(AnnotationDemo.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.annotationAttr().value());
        }
    }
}
泛型
package com.sergio.NewTecl;

import java.util.ArrayList;
import java.util.Collection;

/**
 * 泛型基础信息介绍
 * Created by Sergio on 2015-06-11.
 */
public class GenericDemo {
    public static void main(String[] args) throws Exception {
        //定义String类型的集合
        ArrayList<String> collection1 = new ArrayList<String>();
        collection1.add("abc");
        System.out.println(collection1.get(0));

        ArrayList<Integer> collection2 = new ArrayList<Integer>();
        //判断这两个对象的的字节码是否一样。结果是true,说明字节码一样,编译器生成的字节码会去掉类型信息
        System.out.println(collection1.getClass() == collection2.getClass());
        //使用反射往集合中添加String字符串内容
        collection2.getClass().getMethod("add", Object.class).invoke(collection2, "abc");
        System.out.println(collection2.get(0));

        printCollection(collection2);
    }

    //打印集合元素。此处的?是通配符,表示任意类型
    public static void printCollection(Collection<?> collection) {
        for (Object obj : collection) {
            System.out.println(obj);
        }
    }
}
package com.sergio.NewTecl;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * 对集合进行迭代
 * Created by Sergio on 2015-06-11.
 */
public class GenericDemo1 {
    public static void main(String[] args) {
        HashMap<String, Integer> aMaps = new HashMap<String, Integer>();
        aMaps.put("zhansan", 23);
        aMaps.put("lisi", 43);

        Set<Map.Entry<String, Integer>> entrySet = aMaps.entrySet();
        for (Map.Entry<String, Integer> entry : entrySet) {
            System.out.println(entry.getKey() + ":::" + entry.getValue());
        }
    }
}
    public <T extends Exception> sayException() throws T {
        try {

        } catch (Exception e) {
            throw (T) e;
        }
        return;
    }

泛型类型推断:

根据调用泛型方法时实际传递的参数类型或返回值的类型来对端:

  1. 当某个类型变量只在整个参数列表中的所有参数和返回值的一处被应用了,那么根据调用方法时该处的实际应用类型来确定,及直接根据调用方法时传递的参数类型或返回值来决定泛型参数的类型。如:swap(new String[3], 3,4) -> static <E> void swap(E[] a, int i, int i)
  2. 当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用调用方法时这多处的实际应用类型都对应同一种类型来确定。如:add(3, 5) -> static <T> T add(T a, T b)
  3. 当某个类型变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同的类型,且没有使用返回值,这时候去多个参数中的最大交集类型,如下面这句实际对应类型是Number,编译没有问题,只是运行时出问题:
    fill(new Integer[3], 3, 5) -> static <T> void fill(T[] a, T v)
  4. 当某个性类变量在整个参数列表中的所有参数和返回值中的多处被应用了,如果调用方法时这多处的实际应用类型对应到了不同类型,并且使用返回值,这时候优先考虑返回值的类型,例如:这面这句实际对应的类型是Integer,编译报告错误,将变量x的类型改为Number,则没有了错误,int x -(3, 3.5f) -> static <T> T add(T a, T b)
  5. 参数类型的类型推断具有传递性,下面第一种情况推断实际参数类型为Object,编译没问题,而第二种情况则根据参数化的Vector类实例类型变量直接确定为String类型,编译将出现问题:copy(new Integer[5], new String[5]) -> static <T> void copy(T[] a, T[] b)

泛型的类和方法定义

package com.sergio.NewTecl;

/**
 * 泛型接口
 * Created by Sergio on 2015-06-12.
 */
interface Inter<T> {
    void show(T t);
}
//实现接口
class InterImpl<R> implements Inter<R> {
    public void show(R r) {
        System.out.println("show::" + r);
    }
}
类加载器

类加载器的委托机制

代理类
目标类:doSomeThing(){
           业务功能代码
}

代理类:doSomeThing(){
           //前置系统功能代码
           目标对象.doSomeThing()
           //后置系统功能代码 
}
2015-06-14_111227.png

AOP:系统中存在交叉业务,一个交叉业务就是要切入到系统中的一个方面,交叉业务的编程问题即为面向方面编程,而代理就是来处理此问题。
动态代理技术:要为系统中各种接口的类增加代理功能,需要太多的代理类,而这时候可以通过JVM可以在运行期动态生成出类的字节码,而这可以被用作代理类,即为动态代理类。如果要动态生成代理类,而目标类没有实现接口,可以通过CGLIB第三方类库来生成,

package com.sergio.NewTecl;

import javax.xml.bind.SchemaOutputResolver;
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;

/**
 * 创建动态类及查看其构造方法和成员方法列表信息
 * Created by Sergio on 2015-06-14.
 */
public class ProxyTest {
    public static void main(String[] args) throws Exception {
        //获取代理类的字节码
        Class clazzProxy = Proxy.getProxyClass(Collection.class.getClassLoader(), Collection.class);
        System.out.println(clazzProxy.getName());
        //构造方法
        Constructor[] constructors = clazzProxy.getConstructors();
        for (Constructor constructor : constructors) {
            //获取构造方法名称
            String name = constructor.getName();
            StringBuilder stringBuilder = new StringBuilder(name);
            stringBuilder.append('(');
            Class[] clazzParams = constructor.getParameterTypes();
            for (Class clazzParam : clazzParams) {
                stringBuilder.append(clazzParam.getName()).append(',');
            }
            if (clazzParams != null && clazzParams.length == 0) {
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
            stringBuilder.append(')');
            System.out.println(stringBuilder.toString());
        }

        //方法
        Method[] methods = clazzProxy.getMethods();
        for (Method methodor : methods) {
            //获取构造方法名称
            String name = methodor.getName();
            StringBuilder stringBuilder = new StringBuilder(name);
            stringBuilder.append('(');
            Class[] clazzParams = methodor.getParameterTypes();
            for (Class clazzParam : clazzParams) {
                stringBuilder.append(clazzParam.getName()).append(',');
            }
            if (clazzParams != null && clazzParams.length == 0) {
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            }
            stringBuilder.append(')');
            System.out.println(stringBuilder.toString());
        }


        System.out.println("开始创建实例对象");
        //获得构造方法,主要是现实InvocationHandler是个接口,调用处理处理程序
        Constructor constructor = clazzProxy.getConstructor(InvocationHandler.class);
        //需要实现invocationHandler的接口方法,invoke接受的三个参数为:代理对象,代理对象的那个方法,代理对象方法的参数
        class MyInvocationHander1 implements InvocationHandler {

            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        }
        //动态创建代理对象
        Collection proxy1 = (Collection) constructor.newInstance(new MyInvocationHander1());
        proxy1.clear();//调用collection中的clear方法
        proxy1.size();

        //创建实例的第二种写法
        Collection proxy2 = (Collection) constructor.newInstance(new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                return null;
            }
        });

        //动态创建实例对象第三种写法,
        Collection proxy3 =
            (Collection) Proxy.newProxyInstance(Collection.class.getClassLoader(),
                new Class[] {Collection.class},
                new InvocationHandler() {
                    ArrayList target = new ArrayList<>();

                    @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() + "所用时间" + (endTime - beginTime));
                        return retVal;
                    }
                });
        proxy3.add("xyz");
        proxy3.add("lhm");
        System.out.println(proxy3.size());
    }
}
上一篇 下一篇

猜你喜欢

热点阅读