黑马程序员_日记04(java基础加强01)

来源:互联网 发布:护理专业网络教育 编辑:程序博客网 时间:2024/05/18 01:15

------- <a href="http://www.itheima.com" target="blank">android培训</a>、<a href="http://www.itheima.com" target="blank">java培训</a>、期待与您交流! ----------

--------------------------one一些简单新特性----------------------------------
一:静态导入
 import static java.lang.Math.max;导入Math类中的静态方法max();
 import static java.lang.Math.*;导入Math类中所有的静态方法;
 System.out.println(Math.max(3,6));
 System.out.println(max(3,6));
二:可变参数
 class VariableParameter {
  public static void main(String args[]) {
  
  }
  public static int add(int arg1,int ... args) {
   int sum = arg1;
   for(int i=0;i<args.length;i++) {
    sum = sum + args[i];
   }
   return sum;
  }
 }
 
 1,只能出现在参数列表的最后
 2,add(int arg1,int ... args)/add(int arg1,int...args);
 3,调用可变参数的方法时,编译器为该可变参数隐含创建一个数组,在方法体中以数组的形式访问可变参数
 *overload & override
三:增强for循环
 public static int add(int arg1,int ... args) {
   int sum = arg1;
   for(int arg : args) {
    sum = sum + arg;
   }
   return sum;
  }
四:基本数据类型的自动拆箱与装箱
 public class AutoBox {
  public static void main(Stirng args[]) {
   Integer i = 3;//自动装箱
   System.out.println(i + 12);//自动拆箱
   
   Integer i1 = 3;
   Integer i2 = 3;
   i1 == i2;  (true)
   Integer i3 = 213;
   Integer i4 = 213;
   i3 == i4;   (false)
   
  }
 }
 *享元模式(flyweight):有很多相同的小对象,他们有很多属性相同,把他们变成一个对象,
 把不同的属性变成方法的参数。参数称为外部状态,相同的属性称为内部状态;
 
--------------------------two枚举---------------------------------- 
一:枚举
 /*
 class EnumTest {
  public static void main(String args[]) {
   WeekDay wd = WeekDay.FRI;
   System.out.println(wd);
  }
  
  public enum WeekDay {
   SUN,MON,TUE,WED,THI,FRI,SAT;
  }
 }
 */
 class EnumTest {
  public static void main(String args[]) {
   TrafficLamp t = TrafficLamp.RED.nextLamp();
   int time = TrafficLamp.RED.time;
   System.out.println(t);
   System.out.println(time);
  }
  public enum TrafficLamp {
   RED(30){
    public TrafficLamp nextLamp() {
     return GREEN;
    }
   },
   GREEN(30){
    public TrafficLamp nextLamp() {
     return YELLOW;
    }
   },
   YELLOW(5){
    public TrafficLamp nextLamp() {
     return RED;
    }
   };
   private int time;
   private TrafficLamp(int time) {
    this.time = time;
   }
   public abstract TrafficLamp nextLamp();
  }
 }
--------------------------three反射----------------------------------
一:反射的基石 Class类
 Person p = new Person;
 得到类的字节码3种方式
 Class clazz = Person.class;//字节码
 clazz = p.getClass();
 clazz = Calss.froName("java.lang.String");
 
 Class.forName()的作用:若内存中有相应类的字节码,该函数返回相应的字节码
  若内存中没有相应类的字节码,则调用类加载器将相应的类加载进内存,并返回该类的字节码
 9个预定义Class实例对象:8种基本数据类型和void 
 总之,只要在源程序中出现的类型,都有各自的Class实例对象
二:反射
 1,构造方法的反射使用(constructor类)
 //String s = new String(new StringBuffer("abc"));
 Constructor constructor = String.class.getConstructor(StringBuffer.class);
 //获得方法是要用到类型
 String s = (String)constructor.newInstance(new StringBuffer("abc"));
 //调用获得的方法时要用到上面相同类型的实例对象
 
 Class.newInstance()方法:该方法内部先得到默认的构造方法,然后用该构造方法创建实例对象
 String s = (String)Class.forName("java.lang.String").newInstance();
 2,成员变量的反射(Field类)
 Field field = obj.getClass().getField("name");
 //field不是对象上的变量,而是类上的,
 field.get("obj");//用它取某个对象上的值
 getField("")得到公有的字段,getDeclaredField("")得到所有定义过的字段
 练习:将任意一个对象的所有String类型的
  import java.lang.reflect.*;
  class changeValue {
   public static void main(String args[]) throws Exception{
    person p = new person();
    change(p);
    System.out.println(p);
   }
   public static void change(Object obj) throws Exception{
    Field[] fields = obj.getClass().getFields();
    for(Field field : fields) {
     if(field.getType() == String.class) {
      String olds = (String)field.get(obj);
      String news = olds.replace('b','a');
      field.set(obj,news);
     }
    }
   }
  }

  class person {
   public String name = "abc";
   public String local = "hebei";
   public String sex = "male";
   
   public person() {}
   public person(String name,String local,String sex) {
    super();
    this.name = name;
    this.local = local;
    this.sex = sex;
   }
   public String toString() {
    return name + ":" + local + ":" + sex;
   }
  }
 3,成员方法的反射(Method类:代表类中的一个成员方法)
 class method {
  public static void main(String args[]) throws Exception {
   String s = "abc";
   Method m = s.getClass().getMethod("charAt",int.class);
   System.out.println(m.invoke(s,1));
  }
 }
 //invoke()的第一个参数为null是,则该Method对象对应得是一个静态方法
 对接收数组参数的成员方法进行反射:
 class method1 {
  public static void main(String args[]) throws Exception{
   Method method = person.class.getMethod("main",String[].class);
   //method.invoke(null,(Object)new String[]{});
   //为了兼容,编译器会把数组里的每个元素都当做一个参数
   method.invoke(null,new Object[]{new String[]{}});
  }
 }
 4,数组的反射
 public static void main(String[] args) {
  int[] a1 = new int[4];
  int[][] a2 = new int[2][3];
  String[] s1 = new String[3];
  Object[] obj1 = a1;//编译不能通过,为什么不自动装箱。
  Object[] obj2 = a2;
  Object[] obj3 = s1;
 }
 private static void PrintObj(Object s1) {
  // TODO Auto-generated method stub
  Class clazz = s1.getClass();
  if(clazz.isArray()) {
   int len = Array.getLength(s1);
   for(int i=0;i<len;i++) {
    System.out.println(Array.get(s1, i));
   }
  } else {
   System.out.println(s1);
  }
 }
三:反射的作用——实现框架功能
 1,示例
 class prop{
  public static void main(String[] args) throws Exception {
   // TODO Auto-generated method stub
   InputStream in = new FileInputStream("config.properties");
   //一下为用类加载器管理配置文件
   //InputStream in = prop.class.getClassLoader().getResourceAsStream("config.properties");
   //InputStream in = prop.class.getResourceAsStream("config.properties");
   Properties p = new Properties();
   p.load(in);
   String className = p.getProperty("className1");
   Collection collection = (Collection)Class.forName(className).newInstance();
   collection.add("a");
   collection.add("b");
   collection.add("c");
   collection.add("c");
   System.out.println(collection.size());
  }
 }
 config.properties文件:
 className=java.util.ArrayList
 className1=java.util.HashSet
 /*相对路径是相对当前工作目录
 getRealpath();*/
四:内省(IntroSpector)
 1,
 public class IntroSpactor {
  public static void main(String[] args) throws Exception {
   // TODO Auto-generated method stub
   Person person = new Person(12,"zhangsan");
   String propertyName = "age";
   Class clazz = person.getClass();
   /*PropertyDescriptor pd = new PropertyDescriptor(propertyName, clazz);
   Method methodGetAge = pd.getReadMethod();
   System.out.println(methodGetAge.invoke(person));
   Method methodSetAge = pd.getWriteMethod();
   methodSetAge.invoke(person, 21);
   System.out.println(methodGetAge.invoke(person));*/
   BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
   PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
   for(PropertyDescriptor propertyDescriptor : propertyDescriptors) {
    if(propertyDescriptor.getName().equals("age")) {
     Method methodGetAge = propertyDescriptor.getReadMethod();
     System.out.println(methodGetAge.invoke(person));
     break;
    }
   }
  }
 }