码迷,mamicode.com
首页 > 编程语言 > 详细

黑马程序员_Java基础加强(上)

时间:2014-05-28 03:27:13      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:des   style   c   class   blog   code   

1.静态导入

  静态导入是jdk1.5版本以后出现的新特性,一般是指导入静态方法,如:import static java.lang.System.out 是指导入系统输出的静态方法。

例:

import static java.lang.System.out  //导入java.lang包下的System类的静态方法out

public class StaticImport {

  public static void main(String[] args) {  

    int x=1;   

    x++;   

    out.println(x);  //导入java.lang包下的System类的静态方法out后,可以写成out.println(x);来打印数据x,不必写全System.out.println(x);

  }

}

2.可变参数

  一个方法接受的参数个数不固定如:

System.out.println(add(3,4,5)),

System.out.println(add(1,2,3,4,5)),

可变参数的特点:

只能出现在参数列表最后;

... 位于参数类型和参数名之间前后有无空格都可以

调用可变参数的方法时,编译器为该可变参数隐含创建一个数组,在方法中以数组形式访问参数。

例:

public class VarableParameter {

  public static void main(String[] args) {   

    // TODO Auto-generated method stub   

    System.out.println(add(2,3));   

    System.out.println(add(2,3,5));  

  }  

  public static int add(int x,int ... args){      //可变参数创建格式

    int sum=x;   

    for (int i=0;i<args.length;i++){        

      sum+=args[i];   

    }   

    return sum;  

  }

}

3.增强for循环

  语法:for(type  变量名 :集合变量名)

注意事项:

迭代变量必须在()中定义

集合变量可以是数组或实现了iterable接口的集合类

例:

public class VarableParameter {

  public static void main(String[] args) {  

    // TODO Auto-generated method stub  

    System.out.println(add(2,3));  

    System.out.println(add(2,3,5)); 

  } 

  public static int add(int x,int ... args){      //可变参数创建格式

    int sum=x;  

    for (int arg :args){       

      sum+=arg;  

    }  

    return sum; 

  }

}

4.基本数据类型的拆箱与装箱

自动装箱:

Integer num1 = 12;

自动拆箱:

System.out.println(num1 + 2);

例:

public class AutoBox {

  public static void main(String[] args) {   

    // TODO Auto-generated method stub   

    Integer iObj = 3;   

    System.out.println(iObj + 12);  

  }

}

5.枚举

枚举是要让某个类型的变量的取之只能为若干个固定的值中的一个,否则编译器就会报错,枚举可以让编译器在编译时就可以控制源程序中填写的非法值,普通变量的方式在开发阶段无法实现这一功能。

用普通类如何实现枚举功能,定义一个Weekday的类来模拟枚举功能

私有构造方法;每个元素分别用一个共有的静态成员变量表示;可以有若干构造方法或抽象方法,要提供NextDay()是抽象的。

例:

package cn.itcast.day1;

public abstract class WeekDay1 {    

  private WeekDay1(){}    

  public final static WeekDay1 SUN= new WeekDay1(){

     @Override   

    public WeekDay1 nextDay() {   

       // TODO Auto-generated method stub    

      return MON;   

    }     

  };  

  public final static WeekDay1 MON= new WeekDay1(){

     @Override   

    public WeekDay1 nextDay() {    

      // TODO Auto-generated method stub    

      return SUN;   

    }     

  };    

  public abstract WeekDay1 nextDay();

  /* public WeekDay nextDay(){      

      if(this == SUN){    

        return MON;   

      }else{    

        return SUN;   

      }  

    }*/  

  public String toString(){      

    return this == SUN?"SUN":"MON";  

  }

}

package cn.itcast.day1;

public class EnumTest {

  public static void main(String[] args) {   

    // TODO Auto-generated method stub   

    WeekDay1 weekDay = WeekDay1.MON;   

    System.out.println(weekDay.nextDay());        

    WeekDay weekDay2 = WeekDay.FRI;   

    System.out.println(weekDay2);  

  }

  public enum WeekDay{   

    SUN,MON,TUE,WED,THI,FRI,SAT  

  }  

  //交通灯枚举类 

  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 int time;   

    private TrafficLamp(int time){

      this.time=time;

    }  

  }

}

6.反射

Class 反射的基石

如何得到各个字节码对应的实例对象?

类名.class,例如:System.class ;对象.getClass() 例如:new Date().getClass ; Class.forName("类名") 例如:Class.forName("java.util.Date");

反射就是把Java类中的各种成分映射成相应的Java类。例如一个Java类中用一个Class类的对象来表示,一个类中的组成部分:成员变量,方法,构造方法,包等信息也用一个个Java类来表示就像汽车是一个类,汽车的发动机,变速箱也是一个个的类。表示Java类的Class类显然要提供一系列的方法,来获得其中的变量,方法,构造方法,修饰符,包等信息,这些信息就是用相应类的实例对象来表示,他们是Field、Method、Contructor、Package等等。

例:

bubuko.com,布布扣
package cn.itcast.day1;

import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;


public final class ReflectTest {
    
    public static void main(String[] args) throws Exception{
        
        String str1 = "abc";
        Class cls1 = str1.getClass();
        Class cls2 = String.class ;
        Class cls3 = Class.forName("java.lang.String");
        System.out.println(cls1 == cls2);
        System.out.println(cls1 == cls3);
        
        System.out.println(cls1.isPrimitive());
        System.out.println(int.class.isPrimitive());
        System.out.println(int.class == Integer.class);
        System.out.println(int.class == Integer.TYPE);
        System.out.println(int[].class.isPrimitive());
        System.out.println(int[].class.isArray());
        
        //new String(new StringBuffer ("abc"));
        Constructor constructor1 = String.class.getConstructor(StringBuffer.class);
        String str2 = (String)constructor1.newInstance(new StringBuffer("abc"));
        System.out.println(str2.charAt(2));
        
        ReflectPoint pt1 = new ReflectPoint(3,5);
        Field fieldY = pt1.getClass().getField("y");
        System.out.println(fieldY.get(pt1));
        Field fieldX = pt1.getClass().getDeclaredField("x");
        fieldX.setAccessible(true);
        System.out.println(fieldX.get(pt1));
        
        changeStringValue(pt1);
        System.out.println(pt1);
        
        Method methodCharAt = String.class.getMethod("charAt", int.class);
        System.out.println(methodCharAt.invoke(str1, 1));
        
        //TestArguments.main(new String[]{"111","222","333"});
        String startingClassName = args[0];
        Method mainMethod = Class.forName(startingClassName).getMethod("main", String[].class);
        //mainMethod.invoke(null,new Object[]{new String[]{"111","222","333"}});
        mainMethod.invoke(null,(Object)new String[]{"111","222","333"});
        
        
        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"};
        System.out.println(a1.getClass() == a2.getClass());
        System.out.println(a1.getClass().getName());
        System.out.println(a1.getClass().getSuperclass().getName());
        System.out.println(a4.getClass().getSuperclass().getName());
        System.out.println(a3.getClass().getSuperclass().getName());
        
        Object aobj1 = a1;
        Object aobj2 = a2;
        //Object[] aobj3 = a1;
        Object[] aobj4 = a3;
        Object[] aobj5 = a4;
    
        System.out.println(a1);
        System.out.println(a4);
        System.out.println(Arrays.asList(a1));
        System.out.println(Arrays.asList(a4));
        
        //Object obj = null;
        printObject(a1);
        printObject("abc");
    }

    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));
            }
        }else{
            System.out.println(obj);
        }
        
    }

    private static void changeStringValue(Object obj) throws Exception {
        Field[] fields = obj.getClass().getFields();
        for(Field field : fields){
            //if(field.getType().equals(String.class))
            if(field.getType() == String.class){
                String oldValue = (String)field.get(obj);
                String newValue = oldValue.replace("b", "a");
                field.set(obj,newValue);
            }
        }
        
    }

}
class TestArguments{
    public static void main(String[] args){
        for(String arg : args){
            
            System.out.println(arg);
        }
    }
}
bubuko.com,布布扣
bubuko.com,布布扣
package cn.itcast.day1;

import java.util.Date;

public class ReflectPoint {
    private Date birthDay = new Date();
    public Date getBirthDay() {
        return birthDay;
    }



    public void setBirthDay(Date birthDay) {
        this.birthDay = birthDay;
    }



    private int x;
    public int y;
    public String str1 = "ball";
    public String str2 = "basketball";
    public String str3 = "itcast";
    
    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 ReflectPoint(int x, int y) {
        super();
        this.x = x;
        this.y = y;
    }

    
    
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + x;
        result = prime * result + y;
        return result;
    }



    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        ReflectPoint other = (ReflectPoint) obj;
        if (x != other.x)
            return false;
        if (y != other.y)
            return false;
        return true;
    }



    @Override
    public String toString() {
        return str1+":"+str2+":"+str3;
    }
    

}
bubuko.com,布布扣
bubuko.com,布布扣
package cn.itcast.day1;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Properties;

public class ReflectTest2 {

    public static void main(String[] args) throws Exception{
        // TODO Auto-generated method stub
        
        //InputStream ips = new FileInputStream("config.properties");
        
        //InputStream ips = ReflectTest2.class.getClassLoader().getResourceAsStream("cn/itcast/day1/config.properties");
        //InputStream ips = ReflectTest2.class.getResourceAsStream("resource/config.properties");
        InputStream ips = ReflectTest2.class.getResourceAsStream("/cn/itcast/day1/resource/config.properties");
        
        Properties props = new Properties();
        props.load(ips);
        ips.close();
        String className = props.getProperty("className");
        Collection collections = (Collection)Class.forName(className).newInstance();
        
        //Collection collections = new HashSet();
        ReflectPoint pt1 = new ReflectPoint(3,3);
        ReflectPoint pt2 = new ReflectPoint(5,5);
        ReflectPoint pt3 = new ReflectPoint(3,3);
        collections.add(pt1);
        collections.add(pt2);
        collections.add(pt3);
        collections.add(pt1);
        
        //pt1.y = 7;
        //collections.remove(pt1); //导致内存泄漏
        
        
        System.out.println(collections.size());
    }

}
bubuko.com,布布扣

7.内省——>JavaBean
  JavaBean是一种特殊的Java类,主要用于传递数据信息,这种Java类中的方法主要用于访问私有字段,且方法符合某种命名规则。

例:

bubuko.com,布布扣
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;
import java.util.Map;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class IntroSpectorTest {

    public static void main(String[] args) throws Exception{

        ReflectPoint pt1 = new ReflectPoint(3,5);
        
        String propertyName = "x";
        Object retVal = getProperty(pt1, propertyName);
        System.out.println(retVal);

        Object value = 7;
        
        setProperties(pt1, propertyName, value);

        System.out.println(    BeanUtils.getProperty(pt1,"x").getClass().getName());
        BeanUtils.setProperty(pt1, "x", "9");
        
        System.out.println(pt1.getX());
        //Java7的新特性
        /*Map map = {name : "zxx",age : 18};
        BeanUtils.setProperty(map, "name", "lhm");*/
        BeanUtils.setProperty(pt1, "birthDay.time", "111");
        System.out.println(BeanUtils.getProperty(pt1, "birthDay.time"));
        
        PropertyUtils.setProperty(pt1, "x", 9);
        System.out.println(    PropertyUtils.getProperty(pt1,"x").getClass().getName());
    }


    private static void setProperties(Object pt1, String propertyName,
            Object value) throws IntrospectionException,
            IllegalAccessException, InvocationTargetException {
        PropertyDescriptor pd2 = new PropertyDescriptor(propertyName,pt1.getClass());
        Method methodSetX = pd2.getWriteMethod();
        methodSetX.invoke(pt1,value);
    }

    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);*/
        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;
    }

}
bubuko.com,布布扣

 

 

黑马程序员_Java基础加强(上),布布扣,bubuko.com

黑马程序员_Java基础加强(上)

标签:des   style   c   class   blog   code   

原文地址:http://www.cnblogs.com/jackv/p/3753545.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!