第十章:Java常用类库1.1  StringBuffer类范例1-1:观察StringBuffer基本使用。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                // String类可以直接赋值实例化,但是StringBuffer类不行                StringBuffer buf = new StringBuffer();            // 实例化StringBuffer类对象                buf.append("Hello ").append("MLDN ").append("!!");                change(buf);                                     // 引用传递                System.out.println(buf);        }          public static void change(StringBuffer temp) {        // 接收StringBuffer引用                temp.append("\n").append("www.yootk.com");    // 修改内容        }  }  范例1-2:取得CharSequence接口实例化对象。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                CharSequence seq = "www.yootk.com";     // 向上转型                System.out.println(seq);                 // String类覆写的toString()        }  }  范例1-3:String与StringBuffer比较。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                StringBuffer buf = new StringBuffer("yootk");                System.out.println("yootk".contentEquals(buf));            }  }  范例1-4:字符串反转。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                StringBuffer buf = new StringBuffer("www.yootk.com");                System.out.println(buf.reverse());        }  }  范例1-5:在指定的索引位置增加数据。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                StringBuffer buf = new StringBuffer("yootk");                // 首先在最前面追加一个字符串,然后在指定位置追加字符串                buf.insert(0, "www.").insert(9, ".com");                System.out.println(buf);        }  }  范例1-6:删除部分数据。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                StringBuffer buf = new StringBuffer("Hello World MLDN");                System.out.println(buf.delete(5, 11));        }  }

1.2  Runtime类范例1-7:观察内存大小。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                Runtime run = Runtime.getRuntime();                 // 取得Runtime类的实例化对象                System.out.println("MAX = " + run.maxMemory());    // 取得最大可用内存                System.out.println("TOTAL = " + run.totalMemory());// 取得全部可用内存                System.out.println("FREE = " + run.freeMemory());    // 取得空闲内存        }  }  范例1-8:启动时设置内存大小。java -Xms1024M -Xmx1024M -Xmn512M com.yootk.demo.Test Demo范例1-9:观察gc()使用前后的内存占用率问题。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                Runtime run = Runtime.getRuntime();    // 取得Runtime类的实例化对象                String str = "";                for (int x = 0; x < 2000; x++) {                        str += x;                             // 产生大量垃圾                }                  System.out.println("【垃圾处理前内存量】MAX = " + run.maxMemory());                System.out.println("【垃圾处理前内存量】TOTAL = " + run.totalMemory());                System.out.println("【垃圾处理前内存量】FREE = " + run.freeMemory());                run.gc();                             // 释放垃圾空间                System.out.println("〖垃圾处理后内存量〗MAX = " + run.maxMemory());                System.out.println("〖垃圾处理后内存量〗TOTAL = " + run.totalMemory());                System.out.println("〖垃圾处理后内存量〗FREE = " + run.freeMemory());        }  }  范例1-10:创建“mspaint.exe”(Windows的画板)进程package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                Runtime run = Runtime.getRuntime();             // 取得Runtime类的实例化对象                Process pro = run.exec("mspaint.exe");         // 调用本机可执行程序                Thread.sleep(2000);                            // 运行2s后自动关闭                pro.destroy();                                     // 销毁进程        }  }  1.3  System类范例1-11:请统计出某项操作的执行时间。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                long start = System.currentTimeMillis();         // 取得开始时间                String str = "";                for (int x = 0; x < 30000; x++) {                        str += x;                }                  long end = System.currentTimeMillis();        // 取得结束时间                System.out.println("本次操作所花费的时间:" + (end - start));        }  }  范例1-12:对象回收操作。package com.yootk.demo;class Human {        public Human() {                System.out.println("欢天喜地,一个健康的孩子诞生了。");        }          @Override        protected void finalize() throws Throwable {        // 覆写Object类方法                System.out.println("活了250年,到时候了!");                throw new Exception("此处即使抛出异常对象也不会产生任何影响!");        }  }  public class TestDemo {        public static void main(String[] args) {                Human mem = new Human();                     // 实例化新的对象                mem = null;                                     // 产生垃圾                System.gc();                                     // 手工处理垃圾收集        }  }  1.4  对象克隆范例1-13:实现克隆操作。package com.yootk.demo;class Book implements Cloneable {                     // 此类的对象可以被克隆        private String title;        private double price;        public Book(String title, double price) {                this.title = title;                this.price = price;        }          public void setTitle(String title) {                this.title = title;        }          @Override        public String toString() {                return "书名:" + this.title + ",价格:" + this.price;        }          // 由于此类需要对象克隆操作,所以才需要进行方法的覆写        @Override        public Object clone() throws CloneNotSupportedException {                return super.clone();                             // 调用父类的克隆方法        }  }  public class TestDemo {        public static void main(String[] args) throws Exception {                Book bookA = new Book("Java开发", 79.8);        // 实例化新对象                Book bookB = (Book) bookA.clone();            // 克隆对象,开辟新的堆内存空间                bookB.setTitle("JSP开发");                        // 修改克隆对象属性,不影响其他对象                System.out.println(bookA);                System.out.println(bookB);        }  }  1.5  数字操作类范例1-14:观察四舍五入。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                System.out.println(Math.round(15.5));         // 16                System.out.println(Math.round(-15.5));     // -15                System.out.println(Math.round(-15.51));     // -16        }  }  范例1-15:实现指定位数的四舍五入操作。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                System.out.println(round(-15.678139,2)); // -15.68        }          /**         * 四舍五入操作,可以保留指定长度的小数位数         * @param num 要进行四舍五入操作的数字         * @param scale 保留的小数位         * @return 四舍五入之后的数据         */        public static double round(double num , int scale) {                // Math.pow()的方法作用是进行10的N次方的计算                return Math.round(num * Math.pow(1.0, scale)) / Math.pow(1.0, scale);        }  }  范例1-16:产生10个不大于100的正整数(0~99)。package com.yootk.demo;import java.util.Random;public class TestDemo {        public static void main(String[] args) throws Exception {                Random rand = new Random() ;                for (int x = 0 ; x < 10 ; x ++) {                        System.out.print(rand.nextInt(100) + "、");                }          }  }  范例1-17:实现36选7程序。package com.yootk.demo;import java.util.Random;public class TestDemo {        public static void main(String[] args) throws Exception {                Random rand = new Random();                int data[] = new int[7];             // 开辟一个7个元素的数组,保存生成数字                int foot = 0;                     // 此为数组操作脚标                while (foot < 7) {                 // 不确定循环次数,所以使用while循环                        int t = rand.nextInt(37);     // 生成一个不大于37的随机数                        if (!isRepeat(data, t)) {         // 重复                                data[foot++] = t;         // 保存数据                }                  }                  java.util.Arrays.sort(data);     // 排序                for (int x = 0; x < data.length; x++) {                        System.out.print(data[x] + "、");                }          }          /**         * 此方法主要是判断是否存在重复的内容,但是不允许保存0         * @param temp 指的是已经保存的数据         * @param num 新生成的数据         * @return 如果存在返回true,否则返回false         */        public static boolean isRepeat(int temp[], int num) {                if (num == 0) {         // 没有必要判断了                        return true;         // 直接返回,随后的代码都不再执行                }                  for (int x = 0; x < temp.length; x++) {                        if (temp[x] == num) {                                return true;     // 表示后面的数据不再进行判断                        }                  }                  return false;        }  }  范例1-18:超过double数据范围的计算。package com.yootk.demo;public class TestDemo {        public static void main(String[] args) throws Exception {                System.out.println(Double.MAX_VALUE * Double.MAX_VALUE);// Infinity        }  }  范例1-19:进行BigInteger的演示。package cn.mldn.demo;import java.math.BigInteger;public class TestDemo {        public static void main(String[] args) throws Exception {                BigInteger bigA = new BigInteger("234809234801");    // 大数字A                BigInteger bigB = new BigInteger("8939834789");        // 大数字B                System.out.println("加法结果:" + bigA.add(bigB));                System.out.println("减法结果:" + bigA.subtract(bigB));                System.out.println("乘法结果:" + bigA.multiply(bigB));                System.out.println("除法结果:" + bigA.divide(bigB));                BigInteger result[] = bigA.divideAndRemainder(bigB);                System.out.println("商:" + result[0] + ",余数:" + result[1]);        }  }  范例1-20:完成准确位的四舍五入操作。package cn.mldn.demo;import java.math.BigDecimal;class MyMath {     public static double round(double num, int scale) {        BigDecimal big = new BigDecimal(num);                    // 将数据封装在BigDecimal类中        BigDecimal result = big.divide(new BigDecimal(1), scale,                BigDecimal.ROUND_HALF_UP);                // 除法计算        return result.doubleValue();                             // Number类的方法    }  }  public class TestDemo {    public static void main(String[] args) throws Exception {        System.out.println(MyMath.round(15.5, 0));                 // 计算结果:16        System.out.println(MyMath.round(-15.5, 0));             // 计算结果:-15        System.out.println(MyMath.round(168.98765, 2));             // 计算结果:168.99    }  }  1.6  日期处理类范例1-21:取得当前的日期时间。package com.yootk.demo;import java.util.Date;public class TestDemo {    public static void main(String[] args) throws Exception {        Date date = new Date();        System.out.println(date);         // 输出对象信息    }  }  范例1-22:Date与long间的转换。package com.yootk.demo;import java.util.Date;public class TestDemo {    public static void main(String[] args) throws Exception {        long cur = System.currentTimeMillis();            // 取得当前的日期时间以long型返回        Date date = new Date(cur);                    // 将long转换为Date        System.out.println(date);                    // 输出对象信息        System.out.println(date.getTime());             // 输出对象信息    }  }  范例1-23:将日期格式化显示(Date型数据变为String型数据)。package com.yootk.demo;import java.text.SimpleDateFormat;import java.util.Date;public class TestDemo {    public static void main(String[] args) throws Exception {        Date date = new Date();                    // 实例化Date类对象        // 实例化SimpleDateFormat类对象,同时定义好要转换的目标字符串格式        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");        String str = sdf.format(date);             // 将Date型变为String型        System.out.println(str);    }  }  范例1-24:将字符串转换为日期。package com.yootk.demo;import java.text.SimpleDateFormat;import java.util.Date;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "2005-07-27 07:15:22.111" ;    // 字符串由日期时间组成        // 实例化SimpleDateFormat类对象,同时定义好要转换的目标字符串格式        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;        Date date = sdf.parse(str) ;                // 将字符串变为日期型数据        System.out.println(date);    }  }  范例1-25:观察SimpleDateFormat的自动纠正。package com.yootk.demo;import java.text.SimpleDateFormat;import java.util.Date;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "2005-15-57 77:95:22.111" ;    // 字符串由日期时间组成        // 实例化SimpleDateFormat类对象,同时定义好要转换的目标字符串格式        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS") ;        Date date = sdf.parse(str) ;                // 将字符串变为日期型数据        System.out.println(date);    }  }  范例1-26:取得当前的日期时间。package com.yootk.demo;import java.util.Calendar;public class TestDemo {    public static void main(String[] args) throws Exception {        Calendar cal = Calendar.getInstance();                     // 取得本类对象        StringBuffer buf = new StringBuffer();                    // 保存日期时间数据        buf.append(cal.get(Calendar.YEAR)).append("-");            // 取得年数据        buf.append(cal.get(Calendar.MONTH) + 1).append("-");        // 取得月数据,从0开始        buf.append(cal.get(Calendar.DAY_OF_MONTH)).append(" ");    // 取得天数据        buf.append(cal.get(Calendar.HOUR_OF_DAY)).append(":");    // 取得小时数据        buf.append(cal.get(Calendar.MINUTE)).append(":");            // 取得分钟数据        buf.append(cal.get(Calendar.SECOND));                    // 取得秒数据        System.out.println(buf);    }  }  范例1-27:取得五天之后的日期。package com.yootk.demo;import java.util.Calendar;public class TestDemo {    public static void main(String[] args) throws Exception {        Calendar cal = Calendar.getInstance();                         // 取得本类对象        StringBuffer buf = new StringBuffer();                        // 保存日期时间数据        buf.append(cal.get(Calendar.YEAR)).append("-");                // 取得年数据        buf.append(cal.get(Calendar.MONTH) + 1).append("-");            // 取得月数据,从0开始        buf.append(cal.get(Calendar.DAY_OF_MONTH) + 5).append(" ");    // 取得5天后数据        buf.append(cal.get(Calendar.HOUR_OF_DAY)).append(":");        // 取得小时数据        buf.append(cal.get(Calendar.MINUTE)).append(":");                // 取得分钟数据        buf.append(cal.get(Calendar.SECOND));                        // 取得秒数据        System.out.println(buf);    }  }  1.7  比较器范例1-28:实现二分查找。package com.yootk.demo;import java.util.Arrays;public class TestDemo {    public static void main(String[] args) throws Exception {        int data[] = new int[] { 1, 5, 6, 2, 3, 4, 9, 8, 7, 10 }  ;        java.util.Arrays.sort(data);        // 数组必须排序才可以查找        System.out.println(Arrays.binarySearch(data, 9));    }  }  范例1-29:数组相等比较。package com.yootk.demo;import java.util.Arrays;public class TestDemo {    public static void main(String[] args) throws Exception {        int dataA[] = new int[] { 1, 2, 3 }  ;                // 定义A数组        int dataB[] = new int[] { 1, 2, 3 }  ;                // 定义B数组        System.out.println(Arrays.equals(dataA, dataB));    // 比较是否相等    }  }  范例1-30:数组填充。package com.yootk.demo;import java.util.Arrays;public class TestDemo {    public static void main(String[] args) throws Exception {        int data[] = new int[10];                    // 动态开辟数组        Arrays.fill(data, 3);                    // 填充数组数据        System.out.println(Arrays.toString(data));    // 将数组变为字符串输出    }  }  范例1-31:实现对象数组排序。package com.yootk.demo;import java.util.Arrays;class Book implements Comparable {        // 实现比较器    private String title ;    private double price ;    public Book(String title,double price) {        this.title = title ;        this.price = price ;    }      @Override    public String toString() {        return "书名:" + this.title + ",价格:" + this.price + "\n" ;    }      @Override    public int compareTo(Book o) {                // Arrays.sort()会自动调用此方法比较        if (this.price > o.price) {           return 1 ;         }   else if (this.price < o.price) {           return -1 ;        }   else {           return 0;         }      }  }  public class TestDemo {    public static void main(String[] args) throws Exception {        Book books [] = new Book [] {                 new Book("Java开发实战经典",79.8) ,                 new Book("JavaWEB开发实战经典",69.8) ,                 new Book("Oracle开发实战经典",99.8) ,                 new Book("Android开发实战经典",89.8)         }   ;        Arrays.sort(books);                        // 对象数组排序        System.out.println(Arrays.toString(books));    }  }  范例1-32:利用Comparator接口实现对象数组排序。(1)定义一个类,此类不实现比较器接口。package com.yootk.demo;class Book {     private String title ;    private double price ;    public Book() {}      public Book(String title,double price) {        this.title = title ;        this.price = price ;    }      @Override    public String toString() {        return "书名:" + this.title + ",价格:" + this.price + "\n" ;    }      public void setPrice(double price) {        this.price = price;    }      public void setTitle(String title) {        this.title = title;    }      public double getPrice() {        return price;    }      public String getTitle() {        return title;    }  }  范例1-33:修改测试程序。public class TestDemo {    public static void main(String[] args) throws Exception {        Book books [] = new Book [] {                 new Book("Java开发实战经典",79.8) ,                 new Book("JavaWEB开发实战经典",69.8) ,                 new Book("Oracle开发实战经典",99.8) ,                 new Book("Android开发实战经典",89.8)         }   ;        java.util.Arrays.sort(books,(o1,o2)->{            if (o1.getPrice() > o2.getPrice()) {                return 1;            }   else if (o1.getPrice() < o2.getPrice()) {                return -1;            }   else {                return 0;            }          }  );        System.out.println(java.util.Arrays.toString(books));    }  }  1.8  正则表达式范例1-34:实现字符串的判断。package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "123yootk";        System.out.println(isNumber(str));    }      /**     * 判断字符串是否由数字所组成,在本操作中首先将字符串转换为字符数组,然后循环判断每一位字符     * @param temp 要判断的字符串数据     * @return 如果字符串有非数字、为null、没有数据则返回false,正确返回true     */    public static boolean isNumber(String temp) {        if (temp == null || "".equals(temp)) {        // 字符串数据为空           return false ;        }          char data[] = temp.toCharArray();            // 字符串变为字符数组        for (int x = 0; x < data.length; x++) {           if (data[x] > '9' || data[x] < '0') {    // 有一位字符不是数字              return false;                    // 有则返回false,结束判断           }          }          return true;    }  }  范例1-35:利用正则表达式实现同样的验证。package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "123yootk";        System.out.println(str.matches("\\d+"));    }  }  范例1-36:实现字符串替换。package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "hello*)(*()yootk(*#mldn*";        String regex = "[^a-z]";                         // 此处编写正则        System.out.println(str.replaceAll(regex, ""));            // 字符串替换    }  }  范例1-37:字符串拆分。package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "yootk9mldnyo8798o5555tk";        String regex = "\\d+";                     // [0-9]一位以上        String result[] = str.split(regex);        for (int x = 0; x < result.length; x++) {            System.out.println(result[x]);        }      }  }  范例1-38:验证一个字符串是否是数字,如果是则将其变为double型。提示:要转换的数字可能是整数(10)也可能是小数(1.2),但是绝对不允许出现非数字,并且小数点出现时应该有对应的小数位,正则规则分析分析如图1-6所示。图1-6  正则规则分析 提问:为什么使用“\\d”?以上所给出的正则表达式“\\d+(\\.\\d+)?”中间使用了“\\d”,而正则规定中表示数字的简写符号应该是“\d”,为什么需要使用“\\”?回答:转义字符操作。本书第2章为读者讲解过转义字符的概念,其中“\\”描述的是“\”,所以如果要在字符串中定义“\”则必须使用“\\”,这也就是使用“\\d”(本质是“\d”)的原因了。另外由于“.”可以描述所有的任务,所以也需要为其转义,而“\\.”描述的是“\.”的字符,实际上也属于转义操作。 在图1-6描述的正则规则中,整数位使用“\\d+”描述,表示一位以上的整数位。但是在设计小数位时由于存在小数点(“.”在正则中表示任意字符,所以必须使用“\\”转义)的问题,而且小数点与小数位应该作为整体出现,所以使用了“()”进行声明,而整个小数部分应该出现0次或1次,则使用“?”量词修饰。package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "1.10";        String regex = "\\d+(\\.\\d+)?";         if (str.matches(regex)) {                 // 转型之前要进行验证           System.out.println(Double.parseDouble(str));        }      }  }  范例1-39:判断给定的字符串是否是一个IP地址(IPV4)。提示:以“192.168.1.1”IP地址为例,每一个段可以包含的数字长度为1~3位。package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "192.168.1.1";        String regex = "\\d{1,3}  \\.\\d{1,3}  \\.\\d{1,3}  \\.\\d{1,3}  ";        System.out.println(str.matches(regex));    }  }  范例1-40:给定一个字符串,要求判断其是否是日期格式,如果是则将其转换为Date型数据。本次只验证“年-月-日”的日期格式,其中年包含4位数字,月与日分别包含2位数字。package com.yootk.demo;import java.text.SimpleDateFormat;import java.util.Date;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "2013-08-15";        String regex = "\\d{4}  -\\d{2}  -\\d{2}  ";        // 定义验证规则        if (str.matches(regex)) {                    // 符合规则           Date date = new SimpleDateFormat("yyyy-MM-dd").parse(str);           System.out.println(date);        }      }  }  范例1-41:判断电话号码,一般要编写电话号码满足以下3种格式。·  格式一:51283346,一般长度是7 ~ 8位的数字是电话号码(正则格式为:“\\d{7,8}  ”);·  格式二:01-51283346,区号一般是3 ~ 4位,而且区号和电话之间的“-”只有在出现区号时才出现,正则格式:“\\d{3,4}  -)?\\d{7,8}  ”;·  格式三:(010)-51283346,其中在区号前的括号必须成对出现,这样就需要将括号与区号一起显示,正则格式:“((\\d{3,4}  -)|(\\(\\d{3,4}  \\)-))?\\d{7,8}  ”)。package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "(010)-51283346";        String regex = "((\\d{3,4}  -)|(\\(\\d{3,4}  \\)-))?\\d{7,8}  ";        System.out.println(str.matches(regex));    }  }  范例1-42:验证email地址,对于此验证假设有如下两种不同的格式要求。·  要求格式一:email由字母、数字、“_”(下划线)组成。简单email正则分析如图1-7所示。图1-7  简单email正则分析package com.yootk.demo;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "mldn_lixinghua100@yootk.com";        String regex = "\\w+@\\w+\\.\\w+";        System.out.println(str.matches(regex));    }  }  范例1-43:利用Pattern类实现字符串拆分。package com.yootk.demo;import java.util.Arrays;import java.util.regex.Pattern;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "hello1yootk22mldn333lixinghua";        String regex = "\\d+";        Pattern pattern = Pattern.compile(regex);         // 编译正则        String result[] = pattern.split(str);                 // 拆分字符串        System.out.println(Arrays.toString(result));    }  }  范例1-44:实现字符串验证操作。package com.yootk.demo;import java.util.regex.Matcher;import java.util.regex.Pattern;public class TestDemo {    public static void main(String[] args) throws Exception {        String str = "100";        String regex = "\\d+";        Pattern pattern = Pattern.compile(regex);         // 编译正则        Matcher mat = pattern.matcher(str);             // 进行正则匹配        System.out.println(mat.matches());             // 匹配结果    }  }  1.9  反射机制范例1-45:反射初步操作。package com.yootk.demo;import java.util.Date;                         // 导入所需要的类public class TestDemo {    public static void main(String[] args) throws Exception {        Date date = new Date();                 // 产生实例化对象        System.out.println(date.getClass());        // 直接反射输出    }  }  范例1-46:利用反射实例化对象。package com.yootk.demo;class Book {    public Book() {        System.out.println("********** Book类的无参构造方法 ***********");    }      @Override    public String toString() {        return "《名师讲坛——Java开发实战经典》";    }  }  public class TestDemo {    public static void main(String[] args) throws Exception {        Class> cls = Class.forName("com.yootk.demo.Book");        // 设置要操作对象的类名称        // 反射实例化后的对象返回的结果都是Object类型        Object obj = cls.newInstance();                         // 相当于使用new调用无参构造        Book book = (Book) obj;                                // 向下转型        System.out.println(book);    }  }  范例1-47:利用反射实现工厂设计模式package com.yootk.test;interface Fruit {    public void eat() ;}  class Apple implements Fruit {    @Override    public void eat() {        System.out.println("** 吃苹果!");    }  }  class Orange implements Fruit {    @Override    public void eat() {        System.out.println("** 吃橘子!");    }  }  class Factory {    public static Fruit getInstance(String className) {        Fruit f = null;        try {    // 反射实例化,子类对象可以使用Fruit接收            f = (Fruit) Class.forName(className).newInstance();        }   catch (Exception e) {}          // 此处为了方便不处理异常        return f;    }  }  public class TestFactory {    public static void main(String[] args) {    // 直接传递类名称        Fruit fa = Factory.getInstance("com.yootk.test.Apple") ;        Fruit fb = Factory.getInstance("com.yootk.test.Orange") ;        fa.eat();        fb.eat();    }  }  范例1-48:错误的反射实例化操作。package com.yootk.demo;class Book {    private String title ;    private double price ;    public Book(String title, double price) {        this.title = title ;        this.price = price ;    }      @Override    public String toString() {        return "图书名称:" + this.title + ",价格:" + this.price ;    }  }  public class TestDemo {    public static void main(String[] args) throws Exception {        Class> cls = Class.forName("com.yootk.demo.Book") ;        Object obj = cls.newInstance() ;        // 相当于使用new调用无参构造实例化        System.out.println(obj);    }  }  范例1-49:明确调用类中的有参构造。package com.yootk.demo;import java.lang.reflect.Constructor;class Book {    private String title ;    private double price ;    public Book(String title, double price) {        this.title = title ;        this.price = price ;    }      @Override    public String toString() {        return "图书名称:" + this.title + ",价格:" + this.price ;    }  }  public class TestDemo {    public static void main(String[] args) throws Exception {        Class> cls = Class.forName("com.yootk.demo.Book") ;        // 明确地找到Book类中两个参数的构造,第一个参数类型是String,第二个是double        Constructor> con = cls.getConstructor(String.class,double.class) ;        Object obj = con.newInstance("Java开发实战经典",79.8) ;        // 实例化对象,传递参数内容        System.out.println(obj);    }  }  范例1-50:使用反射操作简单Java类的属性。package com.yootk.demo;import java.lang.reflect.Method;class Book {    private String title ;    public void setTitle(String title) {        this.title = title;    }      public String getTitle() {        return title;    }  }  public class TestDemo {    public static void main(String[] args) throws Exception {        String fieldName = "title" ;                        // 要操作的成员名称        Class> cls = Class.forName("com.yootk.demo.Book") ;    // 取得要操作类的反射对象        Object obj = cls.newInstance() ;                    // 必须实例化对象        // 取得类中的setTitle()方法,由于title需要首字母大写,所以调用init()处理,参数类型为String        Method setMet = cls.getMethod("set" + initcap(fieldName), String.class) ;        // 取得类中的getTitle()方法,本方法不接收参数并且没有返回值类型声明        Method getMet = cls.getMethod("get" + initcap(fieldName)) ;        setMet.invoke(obj, "Java开发实战经典") ;     // 等价于:Book类对象.setTitle("Java开发实战经典")        System.out.println(getMet.invoke(obj));        // 等价于:Book类对象.getTitle()    }      public static String initcap(String str) {            // 首字母大写操作        return str.substring(0, 1).toUpperCase() + str.substring(1) ;    }  }  范例1-51:利用反射直接操作私有成员package com.yootk.demo;import java.lang.reflect.Field;class Book {                                        // 为了演示,所以使用非标准简单Java类    private String title ;                                // 私有属性,并没有定义setter、getter方法}  public class TestDemo {    public static void main(String[] args) throws Exception {        Class> cls = Class.forName("com.yootk.demo.Book");    // 取得反射对象        Object obj = cls.newInstance();                     // 必须给出实例化对象        Field titleField = cls.getDeclaredField("title");            // 取得类中的title属性        titleField.setAccessible(true);                        // 取消封装        titleField.set(obj, "Java开发实战经典");                // 相当于:Book类对象.title = "数据"        System.out.println(titleField.get(obj));                 // 相当于:Book类对象.title    }  }  1.10  国际化范例1-52:输出Locale类对象。package com.yootk.demo;import java.util.Locale;public class TestDemo {    public static void main(String[] args) throws Exception {        Locale loc = Locale.getDefault() ;        // 取得本地默认的Local对象        System.out.println(loc);                // 直接输出loc对象    }  }  范例1-53:直接使用Locale定义的常量对象。package com.yootk.demo;import java.util.Locale;public class TestDemo {    public static void main(String[] args) throws Exception {        Locale loc = Locale.CHINA ;        // 中文语言环境        System.out.println(loc);    }  }  范例1-54:定义com.yootk.demo.Messages.properties文件。# (注释内容)yootk.info = 更多课程请访问:www.yootk.comyootk.info = \u66F4\u591A\u8BFE\u7A0B\u8BF7\u8BBF\u95EE\uFF1Awww.yootk.com范例1-55:读取资源文件。package com.yootk.demo;import java.util.ResourceBundle;public class TestDemo {    public static void main(String[] args) throws Exception {        // 访问的时候一定不要加上后缀,因为默认找到的后缀就是“*.properties”        // 此时的Messages.properties文件一定要放在CLASSPATH路径下        ResourceBundle rb = ResourceBundle.getBundle("com.yootk.demo.Messages");        System.out.println(rb.getString("yootk.info"));    }  }  范例1-56:修改com.yootk.demo.Messages.properties定义。# (注释内容)yootk.info = 更多课程请访问:{0}  ,讲师:{1}  yootk.info = \u66F4\u591A\u8BFE\u7A0B\u8BF7\u8BBF\u95EE\uFF1A{0}  \uFF0C\u8BB2\u5E08\uFF1A{1}  范例1-57:读取数据并且动态设置内容。package com.yootk.demo;import java.text.MessageFormat;import java.util.ResourceBundle;public class TestDemo {    public static void main(String[] args) throws Exception {        // 访问的时候一定不要加上后缀,因为默认找到的后缀就是“*.properties”        // 此时的Messages.properties文件一定要放在CLASSPATH路径下        ResourceBundle rb = ResourceBundle.getBundle("com.yootk.demo.Messages");        System.out.println(MessageFormat.format(rb.getString("yootk.info"),                 "www.yootk.com", "李兴华"));        // 设置两个占位符的内容    }  }  范例1-58:定义中文资源文件——com.yootk.demo.Messages_zh_CN.properties。# (注释内容)yootk.info = 更多课程请访问:{0}  yootk.info = \u66F4\u591A\u8BFE\u7A0B\u8BF7\u8BBF\u95EE\uFF1A{0}  范例1-59:定义英文(英语-美国)资源文件——com.yootk.demo.Messages_en_US.properties yootk.info = More courses, please click: {0}  范例1-60:读取资源文件。package com.yootk.demo;import java.text.MessageFormat;import java.util.Locale;import java.util.ResourceBundle;public class TestDemo {    public static void main(String[] args) throws Exception {        Locale zhLoc = new Locale("zh","CN") ;                // 中国—中文        Locale enLoc = new Locale("en","US") ;                // 英语—美国        ResourceBundle zhRB = ResourceBundle.getBundle(                 "com.yootk.demo.Messages", zhLoc);        // 读取中文资源文件        ResourceBundle enRB = ResourceBundle.getBundle(                 "com.yootk.demo.Messages", enLoc);        // 读取英文资源文件        // 读取资源内容,由于资源本身存在有一个占位符,所以需要设置相应的显示数据        System.out.println(MessageFormat.format(zhRB.getString("yootk.info"),                 "www.yootk.com"));        System.out.println(MessageFormat.format(enRB.getString("yootk.info"),                 "www.yootk.com"));    }  }

java类库详解_【Java系列-4】Java常用类库_详解相关推荐

  1. java transferto_小六六学Netty系列之Java 零拷贝

    前言 文本已收录至我的GitHub仓库,欢迎Star:https://github.com/bin392328206/six-finger种一棵树最好的时间是十年前,其次是现在 我知道很多人不玩qq了 ...

  2. 【java集合框架源码剖析系列】java源码剖析之ArrayList

    注:博主java集合框架源码剖析系列的源码全部基于JDK1.8.0版本. 本博客将从源码角度带领大家学习关于ArrayList的知识. 一ArrayList类的定义: public class Arr ...

  3. 【java集合框架源码剖析系列】java源码剖析之java集合中的折半插入排序算法

    注:关于排序算法,博主写过[数据结构排序算法系列]数据结构八大排序算法,基本上把所有的排序算法都详细的讲解过,而之所以单独将java集合中的排序算法拿出来讲解,是因为在阿里巴巴内推面试的时候面试官问过 ...

  4. jacob 详解 语音_Java系列:Java实现文字转语音

    导入jar包 下载jacob-1.18.zip 并导入jacob.jar.json-20160810.jar.log4j-1.2.17.jar 将解压后的文件中jacob-1.18-x64.dll复制 ...

  5. java sse spring_【SpringBoot WEB 系列】SSE 服务器发送事件详解

    SSE 全称Server Sent Event,直译一下就是服务器发送事件,一般的项目开发中,用到的机会不多,可能很多小伙伴不太清楚这个东西,到底是干啥的,有啥用 本文主要知识点如下: SSE 扫盲, ...

  6. stringbuffer常用方法_第八讲:常用类库API

    一.字符串操作---String类 1.String可以表示一个字符串,不能被继承(最终类)不可变 2.String类实际是使用字符数组存储的 String类的两种赋值方式: (1)一种称为直接赋值. ...

  7. ossutil覆盖_查看选项_命令行工具ossutil_常用工具_对象存储 OSS - 阿里云

    -s, --short-format 显示精简格式,如果未指定该选项,默认显示长格式. --bigfile-threshold 开启大文件断点续传的文件大小阈值,单位为Byte,默认值:100MByt ...

  8. Java面试题系列之Java基础类库(一)

    Java程序员面试题大全系列之Java基础类库(一)                                                                           ...

  9. 告别脚本小子系列丨JAVA安全(6)——反序列化利用链(上)

    0x01 前言 我们通常把反序列化漏洞和反序列化利用链分开来看,有反序列化漏洞不一定有反序列化利用链(经常用shiro反序列化工具的人一定遇到过一种场景就是找到了key,但是找不到gadget,这也就 ...

  10. java源码系列:HashMap底层存储原理详解——4、技术本质-原理过程-算法-取模具体解决什么问题

    目录 简介 取模具体解决什么问题? 通过数组特性,推导ascii码计算出来的下标值,创建数组非常占用空间 取模,可保证下标,在HashMap默认创建下标之内 简介 上一篇文章,我们讲到 哈希算法.哈希 ...

最新文章

  1. 每天一点Linux --- 目录的可执行权限
  2. gitee使用svn_Gitee SVN支持
  3. SQL 流程控制语句 之四 WAITFOR语句介绍
  4. -%3e运算符在c语言中的作用,C语言逻辑运算符知识整理
  5. Docker 多机网络
  6. CodeDay#8:支付宝都在用的容器技术了解一下
  7. mybatis Table book.t_abmin not find
  8. 如何攻克 Android 调试难题?| 技术头条
  9. JS数组关联查找的性能优化
  10. php比赛票数造假算法,PHP可以修改概率的抽奖算法(例如转盘等,个人感觉蛮好用)...
  11. 添加地图图例 Arcengine+C#
  12. 高压油管matlab,高压油管的压力及流量控制
  13. Vmware中win7联网
  14. API Gateway介绍
  15. 【重识云原生】第六章容器6.1.7.2节——cgroups原理剖析
  16. 文旅灯光秀互动应用有什么优势
  17. ERP : 产出控制
  18. [配置]keepalived配置高可用虚拟IP不通
  19. INSERT DESC UPDATE SELECT
  20. html5--2.9新的布局元素(5)-hgroup/address

热门文章

  1. 计算机word表格计算教程F9,word表格计算方法详解
  2. 数据分析与可视化(四)Pandas学习基础一:统计分析基础
  3. c语言有flag的程序,c语言flag(编程flag的用法)
  4. 如何在EXCEL表格中加斜线表头
  5. js从服务器获取word文档,JavaScript-js如何获取word文档页数
  6. 隐藏Excel单元格重要数值,不显示数值
  7. 直流电机驱动c语言程序,单片机PWM控制直流电机驱动程序+仿真+报告
  8. 12V转5V原理图(LM2596)
  9. java通过winrm实现remote powershell
  10. 贪心科技分布式高性能深度实战学习笔记