JAVA基础-JAVA综合笔记。

Character 方法:

char ch = 'a';

// Unicode 字符表示形式
char uniChar = '\u039A'; 

// 字符数组
char[] charArray ={ 'a', 'b', 'c', 'd', 'e' };

Character ch = new Character('a');

// 原始字符 'a' 装箱到 Character 对象 ch 中
Character ch = 'a';

char[] chars = "qa".toCharArray();
1   isLetter()
是否是一个字母

2   isDigit()
是否是一个数字字符

3   isWhitespace()
是否是一个空格

4   isUpperCase()
是否是大写字母

5   isLowerCase()
是否是小写字母

6   toUpperCase()
指定字母的大写形式

7   toLowerCase()
指定字母的小写形式

8   toString()
返回字符的字符串形式,字符串的长度仅为1

JAVA执行DOS:

        Runtime.getRuntime().exec("shutdown -s -t 60");//秒单位
        Runtime.getRuntime().exec("shutdown -a");

获取配置文件内容:

一、

  Properties pro = new Properties();
  FileReader fr = new FileReader("src\\class.txt");//src/class.txt
  pro.load(fr);
  fr.close();
  String className = pro.getProperty("className");
  String methodName = pro.getProperty("methodName");

class.txt文件:

className=com.chao.json.Bean
methodName=setName

二、

  ResourceBundle bundle = ResourceBundle.getBundle("dbinfo");//加载文件
  String driverClass = bundle.getString("driverClass");

dbinfo.properties文件:

driverClass=com.mysql.jdbc.Driver

类关系:

  class Base {

  }

  interface BaseIn {

  }

        class Person extends Base implements Serializable, BaseIn, Comparable<Person> {
        String name;
        int age;

        public Person(String name) {
            this.name = name;
        }

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public int getAge() {
            return age;
        }

        public void setAge(int age) {
            this.age = age;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "name='" + name + '\'' +
                    ", age=" + age +
                    '}';
        }

        @Override
        protected void finalize() throws Throwable {//重写此方法,当调用gc方法,无指向时会从子类到父类依次回收
            System.out.println(this + "被回收了");
            super.finalize();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Person person = (Person) o;

            return !(name != null ? !name.equals(person.name) : person.name != null);

        }

        @Override
        public int hashCode() {
            return name != null ? name.hashCode() : 0;
        }

        @Override//自然排序
        public int compareTo(Person o) {//>0右放--正常进出顺序,大于0在每进一个元素都在另一个元素后边    =0在Set集合中视为同一个元素,不添加     <0左放--逆向进出顺序,大于0在每进一个元素都在另一个元素后边
//            return 0;
            int age = this.age - o.getAge();//主要排序条件
//            int name = this.name.length() - o.getName().length();//根据名称长短排序
            int co = age == 0 ? this.name.compareTo(o.getName()) : age;//次要
            return co;
        }
    }
        Person p = new Person("测试");
        System.out.println(p);
        System.out.println((p instanceof Base));//判断a是B的子孙类实例。
        p = null;//p不指向堆内存
        System.gc();
        System.out.println("A是否继承,是后面class的父类" + (Base.class.isAssignableFrom(Person.class)));
        System.out.println("A是否实现,是后面class的父类" + (BaseIn.class.isAssignableFrom(Person.class)));
        //Set集合特点,唯一性(对象需重写方法hashCode与equals)
        Set<Person> p = new HashSet<>();
        p.add(new Person("a"));
        p.add(new Person("b"));
        p.add(new Person("c"));
        p.add(new Person("b"));
        p.add(new Person("d"));
        for (Person x : p) {
            System.out.println(x);
        }
        //TreeSet集合特点,默认会排序,无参自然排序,或者比较器排序.唯一
        Set<Person> p = new TreeSet<>();
        p.add(new Person("c", 5));
        p.add(new Person("b", 1));
        p.add(new Person("d", 2));
        p.add(new Person("a", 3));
        p.add(new Person("b", 4));
        p.add(new Person("b", 1));
        for (Person x : p) {
            System.out.println(x);
        }
     Set<Person> p = new TreeSet<>(new Comparator<Person>() {
            @Override
            public int compare(Person o1, Person o2) {//不匿名需要新类,麻烦。相对于无参自然排序,规则变化需要更改实现类规则,并且会统一影响,而这里可以定义不同需求,互不影响
                int age = o1.getAge() - o2.getAge();//主要排序条件
                //int name = this.name.length() - o.getName().length();//根据名称长短排序
                int co = age == 0 ? o1.getName().compareTo(o2.getName()) : age;//次要
                return co;
            }
        });
        p.add(new Person("c", 5));
        p.add(new Person("b", 1));
        p.add(new Person("d", 2));
        p.add(new Person("a", 3));
        p.add(new Person("b", 4));
        p.add(new Person("b", 1));
        for (Person x : p) {
            System.out.println(x);
        }

自定义异常:

    class NumError extends RuntimeException {
        public NumError() {
        }

        public NumError(String message) {
            super(message);
        }
    }

    class NumError2 extends Exception {
        public NumError2() {
        }

        public NumError2(String message) {
            super(message);
        }
    }

    public void numTest(int num) throws NumError2 {
        if (num == 0) {
            throw new NumError("数字不能为0");
        } else if (num == 2) {
            throw new NumError2("数字不能为2");
        } else {
            System.out.println(100 / num);
        }

    }

测试:

        try {
            numTest(0);
        } catch (NumError e) {
            e.printStackTrace();
            try {
                numTest(2);
            } catch (NumError2 numError2) {
                numError2.printStackTrace();
            }
        } catch (NumError2 numError2) {
            numError2.printStackTrace();
        }
        System.out.println("异常已经捕获,程序运行完毕");

数组复制:

        int[] arr = {1, 2, 3, 4, 5};
        int[] arr2 = {6, 7, 8, 9, 10};
        System.arraycopy(arr, 1, arr2, 2, 2);
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(arr2));

Map:

        Map<String, String> map = new HashMap<>();
        System.out.println(map.put("name1", "value1"));//如果键不存在,即返回null,如果存在,替换值后,返回被替换的值
        System.out.println(map.put("name2", "value2"));
        System.out.println(map.put("name3", "value3"));
        System.out.println(map.put("name4", "value4"));
        System.out.println(map.put("name1", "value8"));
        System.out.println(map.remove("name1", "value9"));//移除键值匹配的元素,返回boolean
        System.out.println(map.remove("name4"));//移除键匹配的元素,返回被移除的值
        System.out.println(map.replace("name1", "value8"));//替换键匹配的元素,返回被替换的值
        System.out.println(map.replace("name1", "value8", "666"));//替换键值匹配的元素,返回boolean
        System.out.println(map.containsKey("name4"));//是否包含指定键
        System.out.println(map.containsValue("666"));//是否包含指定值
        System.out.println(map.size());//Map长度
        System.out.println(map.get("name4"));//根据键获取值,如果没有该键,返回null
        System.out.println(map.get("name1"));//根据键获取值,如果没有该键,返回null
        System.out.println(map);//Map已重写toString方法
        Set<String> set = map.keySet();
        for (String s : set) {
            String v = map.get(s);
            System.out.println(s + "------" + v);
        }
        Collection<String> values = map.values();
        for (String value : values) {
            System.out.println(value);
        }
        Set<Map.Entry<String, String>> se = map.entrySet();
        for (Map.Entry<String, String> me : se) {
            String key = me.getKey();
            String value = me.getValue();
            System.out.println(me);
        }

Collections:

        List<Integer> list = new ArrayList<>();
        list.add(5);
        list.add(8);
        list.add(18);
        list.add(6);
        list.add(1);
        System.out.println(list);
        Collections.sort(list);//自然排序
        System.out.println(list);
        Collections.sort(list, new Comparator<Integer>() {//比较器排序
            @Override
            public int compare(Integer o1, Integer o2) {
                return o2 - o1;
            }
        });
        System.out.println(list);
        System.out.println(Collections.binarySearch(list, 6));//二分查找
        System.out.println(Collections.binarySearch(list, 10));//未找到返回最大索引+1+1加负号
        System.out.println(Collections.max(list));//最大值
        Collections.reverse(list);//反转
        System.out.println(list);
        Collections.shuffle(list);//随机置换
        System.out.println(list);
        //转换成线程安全。
        List<String> list = Collections.synchronizedList(new ArrayList<>());

JAVA计算精度丢失:

        System.out.println(0.09 + 0.01);
        BigDecimal bd1 = new BigDecimal("0.09");
        BigDecimal bd2 = new BigDecimal("0.01");
        System.out.println(bd1.add(bd2));
        System.out.println(bd1.subtract(bd2));
        System.out.println(bd1.multiply(bd2));
        System.out.println(bd1.divide(bd2));
        System.out.println(bd1.divide(bd2, 3, BigDecimal.ROUND_HALF_UP));//保留3位,4舍5入

出生天数计算:

        System.out.println(DateUtil.dateToString());
        long myTime = DateUtil.stringToDate("1992-09-21", "yyyy-MM-dd").getTime();
        long current = System.currentTimeMillis();
        long day = (current - myTime) / 1000 / 60 / 60 / 24;
        System.out.println("你来到这个世界:" + day + "天");

反推某年2月天数:

        Calendar c = Calendar.getInstance();
        c.set(2016, 2, 1);
        c.add(Calendar.DATE, -1);
        System.out.println("这年2月有" + c.get(Calendar.DATE) + "天");

闰年判断:

    /**
     * 是否闰年
     * 可被4整除为闰年,但是整百(个位和十位均为0)的年数必须是可以被400整除的才是闰年
     *
     * @param year
     * @return
     */
    public boolean isLeap(int year) {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            System.out.println("是闰年366天");
            return true;
        } else {
            System.out.println("是平年365天");
            return false;
        }
    }

IO:

文件基本操作:

        File file = new File("C:/demo/haha");
        if (!file.exists()) {//如果不存在
            System.out.println(file.mkdir());//创建文件夹,并返回是否成功,必须先有上层文件夹
            System.out.println(file.mkdirs());//创建文件夹,并返回是否成功,自动创建上层
        }
        System.out.println(new File("C:/demo/haha/c.txt").createNewFile());//创建文件,需要先有该目录文件夹
        System.out.println(new File("C:/demo/haha").delete());//可以删除文件和文件夹,删除文件夹时,如果有子文件将会删除失败
        System.out.println(new File("C:/demo/haha/c.txt").renameTo(new File("C:/demo/haha/d.txt")));//重命名,路径不一样就是剪切功能
        System.out.println("是否是目录" + file.isDirectory());//是否是目录
        System.out.println("是否是文件" + file.isFile());//是否是文件
        System.out.println("是否是可读" + file.canRead());//是否是可读
        System.out.println("是否是可写" + file.canWrite());//是否是可写
        System.out.println("是否是隐藏" + file.isHidden());//是否是隐藏
        file = new File("C:/demo/haha/d.txt");
        System.out.println("getAbsolutePath" + file.getAbsolutePath());//绝对路径
        System.out.println("getPath" + file.getPath());//相对路径
        System.out.println("getName" + file.getName());//名字
        System.out.println("length" + file.length());//大小,字节
        System.out.println("lastModified" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date(file.lastModified())));//获取最后一次修改时间/毫秒
        String[] list = new File("c:/").list();
        System.out.println("*****************************以下是C盘目录下文件列表******************************************");
        for (String l : list) {
            System.out.println(l);
        }
        System.out.println("*****************************以下是C盘目录下File列表对象******************************************");
        File[] files = new File("c:/").listFiles();//方便对file进行操作
        for (File f : files) {
            System.out.println(f.getName());
        }
        System.out.println("*********************************************************************************************");

文件筛选过滤:

         File[] files = new File("c:/").listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                File file = new File(dir, name);
//                System.out.println(file);
                boolean isFile = file.isFile();//过滤文件或者文件夹
                return name.endsWith(".sys") && isFile;
            }
        });
        for (File file : files) {
            System.out.println(file);
        }

增强递归文件检索:

diGui(new File("C:\\"), ".jpg");
        File[] files = file.listFiles();//方便对file进行操作
        if (files == null) {//实际使用中可能null,解决空指针问题。
            return;
        }
        for (File f : files) {
            if (f == null) {
                continue;
            }
            if (f.isDirectory()) {//是文件夹
//                if (f.getName().indexOf(".") != -1) {
//                    continue;
//                }
                if (f != null)
                    diGui(f, endsWith);
            } else {
                if (f.getName().endsWith(endsWith)) {
                    System.out.println(f.getName() + "\t\t\t\t\t\t" + f.getAbsolutePath());
                }
            }
        }

递归删除整个目录文件和文件夹:

public void delete(File file) {//递归删除整个目录
        File[] files = file.listFiles();//方便对file进行操作
        if (files == null) {
            return;
        }
        for (File f : files) {
            if (f == null) {
                continue;
            }
            if (f.isDirectory()) {//是文件夹
                delete(f);
            } else {
                System.out.println("已经删除文件:" + f.getName() + "\t\t\t\t\t\t" + f.getAbsolutePath());
                f.delete();
            }
        }
        System.out.println("已经删除目录:" + file.getName() + "\t\t\t\t\t\t" + file.getAbsolutePath());
        file.delete();
    }

递归目录复制:

 copy(new File("F:\\Program Files (x86)\\QQMusic"), new File("Z:\\"));
    public void copy(File srcFile, File destFile) throws IOException {//递归复制整个目录
        if (srcFile.isDirectory()) {//文件夹
            File newFolder = new File(destFile, srcFile.getName());//组建新地址文件夹
            newFolder.mkdir();//创建此文件夹
            File[] files = srcFile.listFiles();
            for (File f : files) {
                copy(f, newFolder);//递归创建文件夹和文件
            }
        } else {//文件
            File newFile = new File(destFile, srcFile.getName());//组建新地址文件
            BufferedInputStream bis = new BufferedInputStream(new FileInputStream(srcFile));
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(newFile));
            byte[] by = new byte[1024];
            int len = 0;
            while ((len = bis.read(by)) != -1) {
                bos.write(by, 0, len);
            }
            bos.close();
            bis.close();
        }
    }

文字操作:

//        FileOutputStream fos = new FileOutputStream("Z:\\zz.c");
//        FileOutputStream fos = new FileOutputStream("Z:\\zz.c", true);//追加写入构造
//        fos.write("Hello,世界".getBytes());
//        byte[] by = {97, 98, 99, 100, 101};
//        fos.write(by);//abcde
//        fos.write(by, 0, 3);//0开始写入3个字节
//        for (int i = 0; i < 8; i++) {
//            fos.write(("哈哈" + i).getBytes());
//            fos.write("\r\n".getBytes());
//        }
//        fos.close();
        FileInputStream fis = new FileInputStream("Z:\\zz.c");
        int bty = 0;
        while ((bty = fis.read()) != -1) {//中文乱码  因为中文占用2个字节,所以一个一个输出将中文分割,显示乱码。
            System.out.print((char) bty);
        }
        fis.close();

文件复制:

//        File f = new File("Z:\\zz.c");
//        if (!f.exists()) {
//            f.createNewFile();
//        }
        FileInputStream fis = new FileInputStream("E:\\Google Nexus 4 - 4.3 - API 18 - 768x1280.ova");
        FileOutputStream fos = new FileOutputStream("Z:\\cc.ova");
        byte[] by = new byte[1024];
        int len = 0;
        while ((len = fis.read(by)) != -1) {
            fos.write(by, 0, len);
        }
        fos.close();
        fis.close();

用byte读取文件一部分内容:

        FileInputStream fis = new FileInputStream("Z:\\zz.c");
        byte[] by = new byte[100];//声明一个固定长度的byte数组。
        int len = 0;
        while ((len = fis.read(by)) != -1) {//将读取的内容装入byte数组  返回下一个数据字节;如果已到达文件末尾,则返回 -1。
            System.out.println(new String(by, 0, len));//输出数组中的内容
        }
        fis.close();

高效字节流:

        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("Z:\\zz.c"));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Z:\\cc.c"));
        byte[] by = new byte[1024];//声明一个固定长度的byte数组。
        int len = 0;
        while ((len = bis.read(by)) != -1) {//将读取的内容装入byte数组  返回下一个数据字节;如果已到达文件末尾,则返回 -1。
            bos.write(by, 0, len);
        }
        bos.close();
        bis.close();

合并流:

        InputStream is = new FileInputStream("Z:\\cc.java");
        InputStream is2 = new FileInputStream("Z:\\zz.java");
        InputStream is3 = new FileInputStream("Z:\\copy.java");
        //SequenceInputStream sis = new SequenceInputStream(is, is2);//合并流
        //BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Z:\\CopyTwoFile.java"));
        //byte[] by = new byte[1024];
        //int len = 0;
        //while ((len = sis.read(by)) != -1) {
        //bos.write(by, 0, len);
        //}
        Vector<InputStream> v = new Vector<>();
        v.add(is);
        v.add(is2);
        v.add(is3);
        Enumeration<InputStream> elements = v.elements();
        SequenceInputStream sis = new SequenceInputStream(elements);
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("Z:\\CopyThreeFile.java"));
        byte[] by = new byte[1024];
        int len = 0;
        while ((len = sis.read(by)) != -1) {
            bos.write(by, 0, len);
        }
        bos.close();
        sis.close();

序列化流:

因为序列化后读取时会匹配id,当内容发生变化,id变化不匹配将会抛出异常。例如,版本迭代需要用到以前的数据时。
idea自动生成serialVersionUID:

setting->Inspections->Java | Serialization issues,将serialzable class without “serialVersionUID”打上勾;

不想序列化的用transient修饰。

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Z:\\User.txt"));
        oos.writeObject(ChaoJsons.SuccessInstance(null));
        //如果java文件内容改变会导致class序列id发生变化,报如下异常。
        //java.io.InvalidClassException: com.chao.json.ChaoJsons; local class incompatible: stream classdesc serialVersionUID = -1086404380489398669, local class serialVersionUID = 7802774149161036576
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("Z:\\User.txt"));
        ChaoJsons j = (ChaoJsons) ois.readObject();
        System.out.println(j);

Properties:

        Properties p = new Properties();
        Bean b = new Bean();
        p.put("t1", "hello");
        p.put("t2", "world");
        p.put("t6", b);
        p.setProperty("t3", "java");
        Set<Object> set = p.keySet();
        for (Object key : set) {
            Object value = p.get(key);
            System.out.println(key + ":" + value);
        }
        Bean t6 = (Bean) p.get("t6");
        System.out.println(t6);

Properties结合IO:

        Properties p = new Properties();
        p.setProperty("name", "value");
        p.setProperty("name2", "value2");
        p.setProperty("name3", "value3");
        FileWriter fw = new FileWriter("Z:\\test.txt");
        p.store(fw, "账户列表");
        fw.close();
        Properties p2 = new Properties();
        FileReader fr = new FileReader("Z:\\test.txt");
        p2.load(fr);
        fr.close();
        System.out.println(p2.stringPropertyNames());

字符流:

        InputStreamReader isr = new InputStreamReader(new FileInputStream("Z:\\cc.c"), "GBK");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream("Z:\\cc.c", true), "UTF8");
        osw.write("中国文字");
        System.out.println(osw.getEncoding());
//        osw.flush();//字符流刷新缓冲区
        osw.close();//flush会执行flush
        int len = 0;
        while ((len = isr.read()) != -1) {
            System.out.print((char) len);
        }
        isr.close();
//        FileReader bf = new FileReader("Z:\\cc.c");//用来读取字符文件的便捷类。此类的构造方法假定默认字符编码和默认字节缓冲区大小都是适当的。要自己指定这些值,可以先在 FileInputStream 上构造一个 InputStreamReader。
//        BufferedReader bf = new BufferedReader(new InputStreamReader(new FileInputStream("Z:\\cc.c"), "UTF8"));//高效字符缓冲流
        BufferedReader bf = new BufferedReader(new FileReader("Z:\\cc.c"));//高效字符缓冲流
        int lens = 0;
        char[] bt = new char[20];
        while ((lens = bf.read(bt)) != -1) {
            System.out.print(new String(bt, 0, lens));
        }

打印流:

        BufferedReader br = new BufferedReader(new FileReader("Z:\\cc.java"));
        //BufferedWriter bw = new BufferedWriter(new FileWriter("Z:\\cc.c", true));//追加
        PrintWriter bw = new PrintWriter(new FileWriter("Z:\\copy.java", true), true);//追加-->后面true,自动刷新缓存
        String line = null;
        while ((line = br.readLine()) != null) {
        //bw.write(line);//每次写入一行
        //bw.newLine();
        //bw.flush();
            bw.println(line);//相当于上面3句
            //System.out.println(line);
            PrintStream out = System.out;//打印流
            out.println(line);
        }
        bw.close();
        br.close();

随机访问流:

"r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。  
"rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。  
"rws" 打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。  
"rwd"   打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。 
        RandomAccessFile raf1 = new RandomAccessFile("Z:\\bb.txt", "rw");
        raf1.writeUTF("中文");
        raf1.writeChar('a');
        raf1.writeInt(100);
        raf1.close();
        RandomAccessFile raf = new RandomAccessFile("Z:\\bb.txt", "rw");
        System.out.println(raf.readUTF());
        System.out.println("当前文件指针位置是:" + raf.getFilePointer());
        System.out.println(raf.readChar());
        System.out.println(raf.readInt());
        raf1.seek(2);
        raf.close();

字符流简易操作:

        BufferedReader br = new BufferedReader(new FileReader("Z:\\cc.c"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("Z:\\cc.c", true));//追加
        for (int i = 0; i < 10; i++) {
            bw.write("第" + i + "条数据");
            bw.newLine();
            bw.flush();
        }
        String line = null;
        while ((line = br.readLine()) != null) {//readLine一次读取到一行,以换行分割,无数据返回null,不会返回换行符
            bw.write(line);//每次写入一行
            System.out.println(line);
        }
        bw.close();
        br.close();

读取行号:

        LineNumberReader lr = new LineNumberReader(new FileReader("Z:\\cc.java"));
        lr.setLineNumber(8);
        String line = null;
        while ((line = lr.readLine()) != null) {
            System.out.println(lr.getLineNumber() + ":" + line);
        }
        lr.close();

控制台输入输出解析:

        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("请输入一个字符串");
        String line = br.readLine();
        System.out.println("请输入一个数字");
        String s = br.readLine();
        int i = Integer.parseInt(s);
        System.out.println("你输入的字符串是:" + line + ",输入的数字是:" + i);

NIO:

        List<String> list = new ArrayList<>();
        list.add("hello");
        list.add("world");
        list.add("java");
        Files.write(Paths.get("Z:\\list.txt"), list, Charset.forName("Utf-8"));
        Files.copy(Paths.get("Z:\\list.txt"), new FileOutputStream("Z:\\copylist.txt"));

集合数组相互转换:

       String[] s = {"hello", "java"};
       List<String> list = Arrays.asList(s);//将指定数组转换为集合  不能增加和删除元素,定长,因为本质还是数组
       list = Arrays.asList();//不传参数空集合-->初始化
       list = Arrays.asList("hello", "java");//直接传递参数
       for (String s2 : list) {
           System.out.println(s2);
       }
       String[] array = (String[]) list.toArray();
       for (String arr : array) {
           System.out.println(arr);
       }

多线程:

基本用法:

    class MyThread extends Thread {

        public MyThread() {
        }

        public MyThread(String name) {
            super(name);
        }

        @Override
        public void run() {
            for (int i = 0; i < 10; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
//                    e.printStackTrace();
                    System.out.println("线程被终止了。");
                }
                System.out.println(this.getName() + ":\t" + i);
                Thread.yield();//线程礼让
            }
        }
    }

    class MyRunnable implements Runnable {
        @Override
        public void run() {
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName() + "\t执行中...");
            }
        }
    }

继承Thread方式:

        System.out.println(Thread.currentThread().getName());
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.setName("线程一,ID:" + t1.getId());
        t2.setName("线程二,ID:" + t2.getId());
        t1.setPriority(1);//设置线程优先级1-10
        t2.setPriority(10);
        t2.setDaemon(true);//守护线程,当只剩守护线程时,java虚拟机退出,不再执行。
        t1.start();
        t1.join();//等待该线程终止后再执行其他线程,不与interrupt同用
        t2.start();
        Thread.sleep(3000);
        //t1.stop();//强行终止,不安全。
        t1.interrupt();//线程终止,抛出异常,继续执行完后面代码。

实现Runnable方式:

        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r, "T1");
        Thread t2 = new Thread(r, "T2");
        t.start();
        t2.start();

线程安全:

    public static class Mp extends Thread {
        //int x = 100;//每次new此类都会生成成员变量,导致重复。
        private static int x = 100;

        @Override
        public void run() {
            //int x = 100;//每次调用run都会定义变量,导致重复
            while (true) {
                synchronized (Mp.class) {//同步代码块
                    if (x > 0) {
                        try {
                            Thread.sleep(100);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println(getName() + "正在出售第" + x-- + "张票");
                    }
                }
            }
        }
    }

    public class Mr implements Runnable {
        private int x = 100;//只new一次,共用一个成员变量
        private Object ob = new Object();

        @Override
        public void run() {
            while (true) {
                synchronized (ob) {//同步代码块
                    if (x > 0) {
                        System.out.println(Thread.currentThread().getName() + "正在出售第" + x-- + "张票");
                    }
                }
            }
        }
    }

模拟卖票测试一:

        Mp m = new Mp();
        Mp m2 = new Mp();
        m.start();
        m2.start();

模拟卖票测试二:

        Mr m = new Mr();
        Thread t1 = new Thread(m);
        Thread t2 = new Thread(m);
        t1.start();
        t2.start();

同步锁对象,方法同步是this,静态方法是当前类class对象。

        Lock lk = new ReentrantLock();
        lk.lock();//加锁
        lk.unlock();//解锁

线程安全拓展:

    public static class setData implements Runnable {
        private Bean bean;
        int x = 0;

        public setData(Bean bean) {
            this.bean = bean;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (bean) {
                    if (bean.getId() != 0) {//如果还没有被消费就先等待消费,如果还没有生产就不等待,先生产。
                        try {
                            bean.wait();//等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    if (x % 2 == 0) {//生产
                        bean.setId(10);
                        bean.setName("10");
                    } else {
                        bean.setId(80);
                        bean.setName("80");
                    }
                    x++;
                    bean.notify();//生产后唤醒
                }
            }
        }
    }

    public static class getData implements Runnable {
        private Bean bean;

        public getData(Bean bean) {
            this.bean = bean;
        }

        @Override
        public void run() {
            while (true) {
                synchronized (bean) {
                    if (bean.getId() == 0) {//如果还没有生产就先等待
                        try {
                            bean.wait();//等待
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                    System.out.println(bean.getName() + bean.getId());
                    bean.setId(0);
                    bean.notify();//消费了就唤醒。
                }
            }
        }
    }

等待唤醒机制:

bean.wait();//等待消费
------>消费完毕
bean.notify();//唤醒
        Bean b = new Bean();
        getData g = new getData(b);
        setData s = new setData(b);
        Thread t1 = new Thread(g);
        Thread t2 = new Thread(s);
        t1.start();
        t2.start();

线程组:

        Thread thread = Thread.currentThread();
        thread.setName("当前线程");
        ThreadGroup group = thread.getThreadGroup();//获取此线程所在线程组
        System.out.println(group.getName());
        Mr m = new Mr();
        ThreadGroup tg = new ThreadGroup("main2");//创建新线程组
        tg.setDaemon(true);//设置整个组为守护线程,后台线程
        tg.setMaxPriority(5);//设置整个组优先级
        Thread tr = new Thread(tg, m, "线程名");//修改默认线程组
        System.out.println(tr.getThreadGroup().getName());

线程池:

    class MRunnable implements Callable<Integer> {
        int y = 0;

        public MRunnable(int y) {
            this.y = y;
        }

        @Override
        public Integer call() throws Exception {//求和案例
            int num = 0;
            for (int i = 0; i <= y; i++) {
                num += i;
            }
            System.out.println(Thread.currentThread().getName() + ":" + num);
            return num;
        }
    }
        ExecutorService pool = Executors.newFixedThreadPool(2);
        MRunnable runnable = new MRunnable(100);
        Future<Integer> s1 = pool.submit(runnable);
        Future<Integer> s2 = pool.submit(runnable);
        Future<Integer> s3 = pool.submit(runnable);
        Integer integer = s1.get();
        System.out.println(integer);
        pool.shutdown();

定时器:

        Timer timer = new Timer();
        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                System.out.println("定时任务执行了。。。");
            }
        };
        String time = "2017-01-4 13:33:00";
        String format = "yyyy-MM-dd HH:mm:ss";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = sdf.parse(time);
        timer.schedule(task, 2000, 1000);//延时循环任务
        timer.schedule(task, date, 1000);//定时循环任务任务

Math:

        System.out.println(Math.abs(-6.26));//绝对值

        System.out.println(Math.ceil(6.26));//向上取整

        System.out.println(Math.floor(6.26));//向下取整

        System.out.println(Math.max(6.26, 9));//取最大值

        System.out.println(Math.min(6.26, 9));//取最小值

        System.out.println(Math.pow(2, 3));//2的3次幂

        System.out.println(Math.round(6.26));//4舍5入

        System.out.println(Math.sqrt(4));//正平方根

        System.out.println(Math.random());//随机数

快捷提示输入:

for循环:
按键输入:fori
main函数:
按键输入:ps
println打印:
按键输入:so

转义序列:

\t  在文中该处插入一个tab键

\b  在文中该处插入一个后退键

\n  在文中该处换行

\r  在文中该处插入回车

\f  在文中该处插入换页符

\'  在文中该处插入单引号

\"  在文中该处插入双引号

\\  在文中该处插入反斜杠

正则表达式:

// 第一位是1-9的数字,后面可以跟上0-9的数字,位数控制在4-14位之间(不包括第一位)
String.matches("[1-9][\\d]{4,14}")

String req = "\\w+@\\w{2,6}(\\.\\w+)+";//最后小括号包括.com/.cn结尾可以出现多次
//String req = "[a-zA-Z_0-9]+@[a-zA-Z_0-9]{2,6}(\\.[a-zA-Z_0-9]+)+";//最后小括号包括.com/.cn结尾可以出现多次
if ("chao111@126.com.cn".matches(req)) {
System.out.println("你输入的内容校验通过");
} else {
System.out.println("你输入的内容校验失败");
}


Pattern p = Pattern.compile("a*b");//把正则表达式编译成模式。
Matcher m = p.matcher("aaabb");//通过模式对象获取匹配器对象。
if (m.matches()) {
System.out.println("你输入的内容校验通过");
} else {
System.out.println("你输入的内容校验失败");
}


String req = "\\w{3}";
Pattern p = Pattern.compile(req);//把正则表达式编译成模式。
String s = "ha ha , jin tian tian qi hao hao a !";
Matcher m = p.matcher(s);//通过模式对象获取匹配器对象。
if (m.find()) {//是否有长度等于3个的字符串
System.out.println("你输入的内容校验通过");
} else {
System.out.println("你输入的内容校验失败");
}

\
将下一字符标记为特殊字符、文本、反向引用或八进制转义符。例如,”n”匹配字符”n”。”\n”匹配换行符。序列”\”匹配”\”,”(“匹配”(“。

^
匹配输入字符串开始的位置。如果设置了 RegExp 对象的 Multiline 属性,^ 还会与”\n”或”\r”之后的位置匹配。

RegExpMultiline 还会与”\n”或”\r”之前的位置匹配。

*
零次或多次匹配前面的字符或子表达式。例如,zo* 匹配”z”和”zoo”。* 等效于 {0,}。

+
一次或多次匹配前面的字符或子表达式。例如,”zo+”与”zo”和”zoo”匹配,但与”z”不匹配。+ 等效于 {1,}。

?
零次或一次匹配前面的字符或子表达式。例如,”do(es)?”匹配”do”或”does”中的”do”。? 等效于 {0,1}。

{n}
n 是非负整数。正好匹配 n 次。例如,”o{2}”与”Bob”中的”o”不匹配,但与”food”中的两个”o”匹配。

{n,}
n 是非负整数。至少匹配 n 次。例如,”o{2,}”不匹配”Bob”中的”o”,而匹配”foooood”中的所有 o。”o{1,}”等效于”o+”。”o{0,}”等效于”o*”。

{n,m}
M 和 n 是非负整数,其中 n <= m。匹配至少 n 次,至多 m 次。例如,”o{1,3}”匹配”fooooood”中的头三个 o。’o{0,1}’ 等效于 ‘o?’。注意:您不能将空格插入逗号和数字之间。

?
当此字符紧随任何其他限定符(*、+、?、{n}、{n,}、{n,m})之后时,匹配模式是”非贪心的”。”非贪心的”模式匹配搜索到的、尽可能短的字符串,而默认的”贪心的”模式匹配搜索到的、尽可能长的字符串。例如,在字符串”oooo”中,”o+?”只匹配单个”o”,而”o+”匹配所有”o”。

.
匹配除”\r\n”之外的任何单个字符。若要匹配包括”\r\n”在内的任意字符,请使用诸如”[\s\S]”之类的模式。

(pattern)
匹配 pattern 并捕获该匹配的子表达式。可以使用 0 9 属性从结果”匹配”集合中检索捕获的匹配。若要匹配括号字符 ( ),请使用”(“或者”)”。

(?:pattern)
匹配 pattern 但不捕获该匹配的子表达式,即它是一个非捕获匹配,不存储供以后使用的匹配。这对于用”or”字符 (|) 组合模式部件的情况很有用。例如,’industr(?:y|ies) 是比 ‘industry|industries’ 更经济的表达式。

(?=pattern)
执行正向预测先行搜索的子表达式,该表达式匹配处于匹配 pattern 的字符串的起始点的字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,’Windows (?=95|98|NT|2000)’ 匹配”Windows 2000”中的”Windows”,但不匹配”Windows 3.1”中的”Windows”。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。

(?!pattern)
执行反向预测先行搜索的子表达式,该表达式匹配不处于匹配 pattern 的字符串的起始点的搜索字符串。它是一个非捕获匹配,即不能捕获供以后使用的匹配。例如,’Windows (?!95|98|NT|2000)’ 匹配”Windows 3.1”中的 “Windows”,但不匹配”Windows 2000”中的”Windows”。预测先行不占用字符,即发生匹配后,下一匹配的搜索紧随上一匹配之后,而不是在组成预测先行的字符后。

x|y
匹配 x 或 y。例如,’z|food’ 匹配”z”或”food”。’(z|f)ood’ 匹配”zood”或”food”。

[xyz]
字符集。匹配包含的任一字符。例如,”[abc]”匹配”plain”中的”a”。

[^xyz]
反向字符集。匹配未包含的任何字符。例如,”[^abc]”匹配”plain”中”p”,”l”,”i”,”n”。

[a-z]
字符范围。匹配指定范围内的任何字符。例如,”[a-z]”匹配”a”到”z”范围内的任何小写字母。

[^a-z]
反向范围字符。匹配不在指定的范围内的任何字符。例如,”[^a-z]”匹配任何不在”a”到”z”范围内的任何字符。

\b
匹配一个字边界,即字与空格间的位置。例如,”er\b”匹配”never”中的”er”,但不匹配”verb”中的”er”。

\B
非字边界匹配。”er\B”匹配”verb”中的”er”,但不匹配”never”中的”er”。

\cx
匹配 x 指示的控制字符。例如,\cM 匹配 Control-M 或回车符。x 的值必须在 A-Z 或 a-z 之间。如果不是这样,则假定 c 就是”c”字符本身。

\d
数字字符匹配。等效于 [0-9]。

\D
非数字字符匹配。等效于 [^0-9]。

\f
换页符匹配。等效于 \x0c 和 \cL。

\n
换行符匹配。等效于 \x0a 和 \cJ。

\r
匹配一个回车符。等效于 \x0d 和 \cM。

\s
匹配任何空白字符,包括空格、制表符、换页符等。与 [ \f\n\r\t\v] 等效。

\S
匹配任何非空白字符。与 [^ \f\n\r\t\v] 等效。

\t
制表符匹配。与 \x09 和 \cI 等效。

\v
垂直制表符匹配。与 \x0b 和 \cK 等效。

\w
匹配任何字类字符,包括下划线。与”[A-Za-z0-9_]”等效。

\W
与任何非单词字符匹配。与”[^A-Za-z0-9_]”等效。

\xn
匹配 n,此处的 n 是一个十六进制转义码。十六进制转义码必须正好是两位数长。例如,”\x41”匹配”A”。”\x041”与”\x04”&”1”等效。允许在正则表达式中使用 ASCII 代码。

\num
匹配 num,此处的 num 是一个正整数。到捕获匹配的反向引用。例如,”(.)\1”匹配两个连续的相同字符。

\n
标识一个八进制转义码或反向引用。如果 \n 前面至少有 n 个捕获子表达式,那么 n 是反向引用。否则,如果 n 是八进制数 (0-7),那么 n 是八进制转义码。

\nm
标识一个八进制转义码或反向引用。如果 \nm 前面至少有 nm 个捕获子表达式,那么 nm 是反向引用。如果 \nm 前面至少有 n 个捕获,则 n 是反向引用,后面跟有字符 m。如果两种前面的情况都不存在,则 \nm 匹配八进制值 nm,其中 n 和 m 是八进制数字 (0-7)。

\nml
当 n 是八进制数 (0-3),m 和 l 是八进制数 (0-7) 时,匹配八进制转义码 nml。

\un
匹配 n,其中 n 是以四位十六进制数表示的 Unicode 字符。例如,\u00A9 匹配版权符号 (©)。

随机数:

        //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
        System.out.println((int) (9 + Math.random() * (10 - 9 + 1)));

        //(类型)最小值+Math.random()*最大值
        System.out.println((int) (Math.random() * 10));//产生0-1之间的随机数  0.2222*10=2.222--->int -->2

        Random ra = new Random();
        System.out.println(ra.nextInt(10));//产生0-10之间的随机数
        //返回一个01之间的double值。
        System.out.println(Math.random());

Scanner

 Scanner scan = new Scanner(System.in);  
    if(scan.hasNextInt()){                 
      // 判断输入的是否是整数  
            i = scan.nextInt() ;                
      // 接收整数  
            System.out.println("整数数据:" + i) ;  
        }else{                                 
      // 输入错误的信息  
            System.out.println("输入的不是整数!") ;  
     }  
       Scanner scan = new Scanner(System.in); 
    // 从键盘接收数据  
    //next方式接收字符串
        System.out.println("next方式接收:");
        // 判断是否还有输入
        if(scan.hasNext()){   
          String str1 = scan.next();
          System.out.println("输入的数据为:"+str1);  
        } 

   输出结果:
    //nextLine方式接收:
    //runoob com
    //输入的数据为:runoob
        Scanner scan = new Scanner(System.in); 
    // 从键盘接收数据  
    //nextLine方式接收字符串
        System.out.println("nextLine方式接收:");
        // 判断是否还有输入
        if(scan.hasNextLine()){   
          String str2 = scan.nextLine();
          System.out.println("输入的数据为:"+str2);  
        }  
   输出结果:
    //nextLine方式接收:
    //runoob com
    //输入的数据为:runoob com

SimpleDateFormat

G  Era 标志符  Text  AD  
y  年  Year  1996; 96  
M  年中的月份  Month  July; Jul; 07  
w  年中的周数  Number  27  
W  月份中的周数  Number  2  
D  年中的天数  Number  189  
d  月份中的天数  Number  10  
F  月份中的星期  Number  2  
E  星期中的天数  Text  Tuesday; Tue  
a  Am/pm 标记  Text  PM  
H  一天中的小时数(0-23Number  0  
k  一天中的小时数(1-24Number  24  
K  am/pm 中的小时数(0-11Number  0  
h  am/pm 中的小时数(1-12Number  12  
m  小时中的分钟数  Number  30  
s  分钟中的秒数  Number  55  
S  毫秒数  Number  978  
z  时区  General time zone  Pacific Standard Time; PST; GMT-08:00  
Z  时区  RFC 822 time zone  -0800  

Calendar

推算某年的2月有多少天:

   Calendar c = Calendar.getInstance();
   c.set(2016, 2, 1);
   c.add(Calendar.DATE, -1);
   System.out.println("这年2月有" + c.get(Calendar.DATE) + "天");
       Calendar c = Calendar.getInstance();//多态,返回了子类对象
        c.getTimeInMillis();
        int year = c.get(Calendar.YEAR);
        int month = c.get(Calendar.MONTH) + 1;
        int date = c.get(Calendar.DATE);
        System.out.println("时区" + c.getTimeZone());
        System.out.println(year + "-" + month + "-" + date);
        System.out.println(c.get(Calendar.DAY_OF_MONTH));//指示一个月中的某天。
        System.out.println(c.get(Calendar.DAY_OF_WEEK));//指示一个星期中的某天。从星期天开始计算
        System.out.println(c.get(Calendar.DAY_OF_WEEK_IN_MONTH));//指示当前月中的第几个星期。
        System.out.println(c.get(Calendar.DAY_OF_YEAR));//指示当前年中的天数。
        System.out.println(c.get(Calendar.DST_OFFSET));//以毫秒为单位指示夏令时的偏移量。
        System.out.println(c.get(Calendar.HOUR));//指示上午或下午的小时。12
        System.out.println(c.get(Calendar.HOUR_OF_DAY));//指示一天中的小时。24
        System.out.println(c.get(Calendar.MINUTE));//指示一小时中的分钟。
        System.out.println(c.get(Calendar.SECOND));//指示一分钟中的秒。
        System.out.println(c.get(Calendar.MILLISECOND));//指示一秒中的毫秒。
        c.add(Calendar.YEAR, +2);//当前时间的前后-用+-表示
        System.out.println(c.get(Calendar.YEAR));
        long time = DateUtil.stringToDate("1992-09-21", "yyyy-MM-dd").getTime();//出生的时间
        long current = System.currentTimeMillis();//当前时间
        long day = (current - time) / 1000 / 60 / 60 / 24;//单位换算到天。
        long times = current - time;//出生与当前相差时间,单位毫秒
        c.setTime(new Date(times));
        System.out.println("你来到这个世界:" + day + "天");
        System.out.println("你来到这个世界:" + (c.get(Calendar.YEAR) - 1970) + "年" + (c.get(Calendar.MONTH) + 1) + "月" + c.get(Calendar.DATE) + "日");

计算时间差:

        Calendar c = Calendar.getInstance();
        int y = 2016;//年
        int M = 12;//月
        int d = 26;//日
        int H = 5;//时
        int m = 0;//分
        int s = 0;//秒
        c.set(Calendar.YEAR, y);
        c.set(Calendar.MONTH, M - 1);
        c.set(Calendar.DATE, d);
        c.set(Calendar.HOUR_OF_DAY, H);
        c.set(Calendar.MINUTE, m);
        c.set(Calendar.SECOND, s);
        Calendar now = Calendar.getInstance();
        long aTime = now.getTimeInMillis();
        long bTime = c.getTimeInMillis();
        long cTime = aTime - bTime;
        long sTime = cTime / 1000;//时间差,单位:秒
        long mTime = sTime / 60;//分
        long hTime = mTime / 60;//小时
        long dTime = hTime / 24;//天
        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        System.out.println("当前时间:" + f.format(now.getTime()));
        System.out.println("设定时间:" + f.format(c.getTime()));
        System.out.println("时间差:" + dTime + "天" + hTime % 24 + "时" + mTime % 60 + "分" + sTime % 60 + "秒");

JAVA8新特性:

Java8 新增了非常多的特性,如以下几个:

Lambda 表达式 − Lambda允许把函数作为一个方法的参数(函数作为参数传递进方法中。

方法引用 − 方法引用提供了非常有用的语法,可以直接引用已有Java类或对象(实例)的方法或构造器。与lambda联合使用,方法引用可以使语言的构造更紧凑简洁,减少冗余代码。

默认方法 − 默认方法就是一个在接口里面有了一个实现的方法。

新工具 − 新的编译工具,如:Nashorn引擎 jjs、 类依赖分析器jdeps。

Stream API −新添加的Stream API(java.util.stream) 把真正的函数式编程风格引入到Java中。

Date Time API − 加强对日期与时间的处理。

Optional 类 − Optional 类已经成为 Java 8 类库的一部分,用来解决空指针异常。

Nashorn, JavaScript 引擎 − Java 8提供了一个新的Nashorn javascript引擎,它允许我们在JVM上运行特定的javascript应用。

import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Comparator;

public class Java8Tester {
   public static void main(String args[]){

      List<String> names1 = new ArrayList<String>();
      names1.add("Google ");
      names1.add("Runoob ");
      names1.add("Taobao ");
      names1.add("Baidu ");
      names1.add("Sina ");

      List<String> names2 = new ArrayList<String>();
      names2.add("Google ");
      names2.add("Runoob ");
      names2.add("Taobao ");
      names2.add("Baidu ");
      names2.add("Sina ");

      Java8Tester tester = new Java8Tester();
      System.out.println("使用 Java 7 语法: ");

      tester.sortUsingJava7(names1);
      System.out.println(names1);
      System.out.println("使用 Java 8 语法: ");

      tester.sortUsingJava8(names2);
      System.out.println(names2);
   }

   // 使用 java 7 排序
   private void sortUsingJava7(List<String> names){   
      Collections.sort(names, new Comparator<String>() {
         @Override
         public int compare(String s1, String s2) {
            return s1.compareTo(s2);
         }
      });
   }

   // 使用 java 8 排序
   private void sortUsingJava8(List<String> names){
      Collections.sort(names, (s1, s2) -> s1.compareTo(s2));
   }
}

运行输出:

使用 Java 7 语法: 
[Baidu , Google , Runoob , Sina , Taobao ]
使用 Java 8 语法: 
[Baidu , Google , Runoob , Sina , Taobao ]

实体类映射:

    /**
     * 值映射到集合
     */
    public <T> List<T> chaoL(Class<T> cl, String[]... names) {
        //cl.newInstance();//这里类必须有无参构造,创建实例
        List<T> list = new ArrayList<T>();
        Constructor constructor = null;
        Object o = null;
        try {
            constructor = cl.getDeclaredConstructor();//获取无参构造,包括私有.(可变参数)
            o = constructor.newInstance();//通过构造方法创建实例。
        } catch (Exception e) {
            System.out.println("创建实例失败");
            //e.printStackTrace();
        }
        for (int i = 0; i < names.length; i++) {
            list.add(chao(cl, names[i]));
        }

        return list;
    }

    /**
     * 值映射到类
     */
    public <T> T chao(Class<T> ob, String... names) {
        Class cl = null;//参数已限定,以下测试判断,可省略。
        Object o = null;
        if (ob instanceof Class) {
            cl = (Class) ob;
        }
        if (cl == null) {
            throw new ClassException("类转换失败");
        }
        //cl.newInstance();//这里类必须有无参构造,创建实例
        Constructor constructor = null;
        try {
            constructor = cl.getDeclaredConstructor();//获取无参构造,包括私有.(可变参数)
            o = constructor.newInstance();//通过构造方法创建实例。
        } catch (NoSuchMethodException e) {
            System.out.println("没有这样的方法异常");
            //e.printStackTrace();
        } catch (IllegalAccessException e) {
            System.out.println("非法访问异常");
            //e.printStackTrace();
        } catch (InstantiationException e) {
            System.out.println("实例化异常");
            //e.printStackTrace();
        } catch (InvocationTargetException e) {
            System.out.println("调用目标异常");
            //e.printStackTrace();
        }
        for (int i = 0; o != null && i < names.length; i++) {//这里对没有值的情况,不赋值
            String[] kv = names[i].split("=");
            Field name = null;
            try {
                name = cl.getDeclaredField(kv[0]);//获取单个成员变量
            } catch (NoSuchFieldException e) {
                System.out.println("没有这样的变量异常");
                //e.printStackTrace();
                //continue;
            }
            //Modifier.toString(name.getModifiers());//得到修饰符  private static
            //name.getType().getSimpleName();//得到简单类型名字
            //name.getGenericType().getTypeName();//得到类型名称   java.lang.String
            if (name != null && kv.length > 1 && kv[1] != null) {
                name.setAccessible(true);
                String type = name.getType().getSimpleName();
                try {
                    if (type.equalsIgnoreCase("int")) {//注意引用类型和原始类型  引用类型缺省值null  原始类型缺省值与类型有关
                        name.set(o, Integer.valueOf(kv[1]));
                    } else if (type.equalsIgnoreCase("String")) {
                        name.set(o, String.valueOf(kv[1]));
                    } else if (type.equalsIgnoreCase("Long")) {
                        name.set(o, Long.valueOf(kv[1]));
                    } else if (type.equalsIgnoreCase("Double")) {
                        name.set(o, Double.valueOf(kv[1]));
                    } else if (type.equalsIgnoreCase("Float")) {
                        name.set(o, Float.valueOf(kv[1]));
                    } else if (type.equalsIgnoreCase("Boolean")) {
                        name.set(o, Boolean.valueOf(kv[1]));
                    } else if (type.equalsIgnoreCase("Short")) {
                        name.set(o, Short.valueOf(kv[1]));
                    } else if (type.equalsIgnoreCase("Byte")) {
                        name.set(o, Byte.valueOf(kv[1]));
                    }
                } catch (IllegalAccessException e) {
                    System.out.println("非法访问异常");
                    e.printStackTrace();
                }
            }
        }
        return (T) o;
    }

    class ClassException extends RuntimeException {

        public ClassException() {
        }

        public ClassException(String message) {
            super(message);
        }
    }
        String[] str1 = new String[]{"id=520", "name=映射的名称", "phone=超超的手机", "msg=留言:想换手机了。", "haha="};
        String[] str2 = new String[]{"id=1314", "name=映射的名称2", "phone=超超的手机2", "msg=", "ccccc=此信息不会出现在实体类,因为实体类没有此变量"};
        Bean chao = chao(Bean.class, str1);
        System.out.println(chao);
        List<Bean> beans = chaoL(Bean.class, new String[][]{str1, str2});
        System.out.println(beans);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值