长文慎点,Java学习笔记(五)

这只是一篇我自己学习java的流水账笔记,包含了以下内容,全是基础代码示例,希望对正在学习java的小伙伴有帮助

  • java编码:编码相关
  • java常用代码:Java常用代码示例
  • jdbc示例:JDBC编程示例

编码相关

  • 隐式类型转换:计算时自动将容量小的类型转换为容量大的类型:byte,short,char->int->long->float->double. important(整数默认是int ,定义byte应该这样定义: byte b = (byte)12 , 浮点数默认是double , 因此,定义float应该这样定义: float f = 12.4f),总之记得一点:大数转换成小数记得加上强制转换!
  • 关于int强制转换为byte的问题(默认byte(1字节)的范围在-128~127,如果把int(4字节)的254强制转换成byte,会砍掉多余字节) , 关于原码,反码,补码的文章, 二进制补码百度百科, 二进制加法 [重说三 : 计算机内部用补码来表示数字,正数(最高位是0)原码=反码=补码 ,负数(最高位是1)三码需要转换]
public class Test{
    public static void main(String[] args){
        byte b1 = (byte)254;//强制转换成byte
        System.out.println(b1);//结果输出-2
         
        byte b2 = (byte)300;
        System.out.println(b2);//结果输出44,正数原码和补码相同
             
        byte b3 = (byte)(-1);
        System.out.println(b3);//打印-1
             
    }
}
/*
解释b1:
1:int的254表示为二进制(正数:原=反=补): 0000 0000 0000 0000 0000 0000 1111 1110(补)
2:强制转换成byte,丢掉前面三个字节,留下(最高位是1,表示负数): 1111 1110(补)
3:补码转反码(最高位符号位不变,其余取反): 1111 1110(补) -->> 1000 0001(反)
4:反码求原码: 1000 0001(反) + 0000 0001 = 1000 0010(原)
5:因此: 1000 0010表示-2
*/
/*
解释b2:
1:int的300表示为二进制(正数:原=反=补): 0000 0000 0000 0000 0000 0001 0010 1100(补)
2:强制转换成byte,丢掉前面三个字节,留下(最高位是0,表示正数): 0010 1100(补)
3:正数原码和补码相同,原码为:0010 1100(原)
4:因此: 0010 1100表示44
*/
/*
解释b3:
1:int的(-1)的原码为:1000 0000 0000 0000 0000 0000 0000 0001(原)
2:原码求反码:1111 1111 1111 1111 1111 1111 1111 1110(反)
3:反码求补码:1111 1111 1111 1111 1111 1111 1111 1111(补)
4:强制转换成byte,丢掉前面三个字节,留下(最高位是1,表示负数): 1111 1111(补)
5:补码求反码:1000 0000(反)
6:反码求原码:1000 0001(原)
7:因此:1000 0001表示-1
*/

Java网络编程示例

TCP多线程

package com.scriptwang.test;
 
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
 
/**
 * Created by ScriptWang on 16/11/28.
 * Java TCP多线程编程模型;
 * 1 : MutiThreadNetwork 的主线程只负责监听请求(accept方法是阻塞的),当有客户端连接的时候交给新线程去处理
 * 2 : 当Socket连接上之后,可以通过getInput(Output)Strean当作普通的流对待
 *
 */
public class MutiThreadNetwork {
    public static final int PORT = 8888;
 
    public static void main(String[] args) {
        new MutiThreadNetwork().run();
    }
 
    public void run() {
        ServerSocket ss = null;
        Socket s = null;
        try {
            ss = new ServerSocket(PORT);//抛IOException
            print("ss ok !");
 
 
            /**
             * 重点:
             * ServerSocket的accept方法是阻塞式的,如果没有人连接,就会一直等待在那里
             * 并且其会抛出IOException
             */
            while ((s = ss.accept()) != null) {
                print("s is ok!");
                new Thread(new SocketThread(s)).start();
            }
 
        } catch (IOException e) {
            e.printStackTrace();
        }
 
    }
 
    class SocketThread implements Runnable {
        private Socket s;
 
        SocketThread(Socket s) {
            this.s = s;
        }
 
        @Override
        public void run() {
            OutputStream out = null;
            DataOutputStream dos = null;
            try {
                out = s.getOutputStream();//抛IOException
                dos = new DataOutputStream(out);
                dos.writeUTF("Test message!");//抛IOException
                out.close();
                s.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
 
    }
    public static void print(Object o) {
        System.out.println(o);
    }
}
 
/**
 * Client 类
 */
class Client {
    public static final int PORT = 8888;
    public static void main(String[] args){
        new Client().run();
    }
    public void run(){
        Socket s = null;
        DataInputStream dis = null;
        String value = null;
        try {
            s = new Socket("localhost", PORT);//抛IOexception
            dis = new DataInputStream(s.getInputStream());
            value = dis.readUTF();//抛IOException
            dis.close();
            s.close();
        }catch (IOException e){
            e.printStackTrace();
        }
 
        print(value);
 
    }
 
    public static void print(Object o){
        System.out.println(o);
    }
}

WEB服务器

package com.scriptwang.test;
 
 
import java.io.IOException;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
 
/**
 * Created by ScriptWang on 16/11/28.
 * 模拟Web服务器,浏览器发起一个请求相当于建立了一个Socket
 * 当服务器accept到一个Socket之后交给对应的线程去处理
 * 新线程会拿到当前Socket并用PrintWriter println数据给浏览器
 *
 *
 * 在流编程中,flush和close很重要!!!!!!!!!!!!!!!!!!!!
 */
public class WEBServer {
    public static final int PORT = 8080;
    public static void main(String[] args){
        new WEBServer().run();
    }
    public void run(){
        ServerSocket ss = null;
        try {
            ss = new ServerSocket(PORT);
            print("ServerSocket is ready!");
 
            //循环来自客户端的请求
            for (Socket s = ss.accept(); s != null; s = ss.accept()){
                new Thread(new WebThread(s)).start();
                print("new Thread is start!");
            }
        }catch (IOException e){
            e.printStackTrace();
        }
 
 
    }
 
    /**
     * 新的线程类
     */
    class WebThread implements Runnable{
        Socket s;
        WebThread(Socket s){
            this.s = s;
        }
        @Override
        public void run(){
            PrintWriter pw = null;
            try{
                pw = new PrintWriter(s.getOutputStream());
                pw.println("");
                pw.println("

Test Message

"
); pw.println(""); /** * flush很重要,虽然PrintWriter有自动flush功能 */ pw.flush(); /** * close很重要,如果不close,浏览器会一直转圈圈, * 以为你还有东西要println给他,其实你已经println完了 * 浏览器还在傻傻的等待 */ pw.close(); }catch (IOException e){ e.printStackTrace(); } } } public static void print(Object o){ System.out.println(o); } }

UDP简单聊天应用

package com.scriptwang.test;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
 
/**
 * Created by ScriptWang on 16/11/29.
 * UDP简单聊天应用,注意以下几点
 *
 * 1: 基本思路:发送和接收消息各用一个线程,互不干扰
 *
 * 2: System.in本身不阻塞,当用BufferedReader怼到
 *    System.in上的时候,BufferedReader的readLine
 *    会阻塞当读取不到数据的时候,readLine会傻傻等待
 *    直到读取到数据等的时候才会继续向下执行
 *
 * 3: DatagramSocket的receive(DataPacket dp)方法
 *    会阻塞,当读取不到数据肚饿时候会傻傻的等待在那里
 *
 */
public class BasicUDP {
 
    public static void main(String[] args) {
        //监听端口,对方ip,对方接受端口
        new Thread(new BasicUDP().new SendThread(8080,"127.0.0.1",9125)).start();
 
        //我方接收端口
        new Thread(new BasicUDP().new ReceiveThread(7777)).start();
    }
 
 
    class SendThread implements Runnable{
 
        public final int SENDPORT;
        public final int YOURPORT;
        public final String IP;
        DatagramSocket ds = null;
        DatagramPacket dp = null;
 
        SendThread(int port0,String ip,int port1){
            this.SENDPORT = port0;
            this.IP = ip;
            this.YOURPORT = port1;
            try {
                ds = new DatagramSocket(SENDPORT);
            }catch (SocketException e){
                e.printStackTrace();
            }
        }
 
        @Override
        public void run(){
 
            //System.in本身不会阻塞,当和br结合的时候,br的readLine读取不到命令行输入的数据时会阻塞
            //当br结合FileInputStream从文本文件读取的时候不会阻塞,因为文本文件始终有数据
 
            //总结:br的readLine读取不到数据的时候会阻塞
            //比如:readLine和System.in结合会阻塞
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
 
            try{
 
                /**
                 * 执行for循环第一句话的时候,readLine会阻塞等待键盘输入
                 * 输入后执行for 循环体
                 * 返回for检查条件语句,发现line并不是null(line的值为上一次谁人的数据)
                 * 执行for的第三句话,这个时候又会阻塞(等待从命令行读入数据)
                 * 如此循环.......loop loop loop.....
                 */
                for ( String line = br.readLine() ; line != null ; line = br.readLine()){
                    dp = new DatagramPacket(line.getBytes(),0,line.getBytes().length,InetAddress.getByName(IP),YOURPORT);
                    ds.send(dp);
                    print(line + " has sended !");
                }
 
            }catch (IOException e){
                e.printStackTrace();
            }
 
        }
    }
 
 
    class ReceiveThread implements Runnable{
        public final int RECEIVEPORT;
 
        DatagramSocket ds = null;
        DatagramPacket dp = null;
        byte[] packet = null;
 
        ReceiveThread(int port){
            this.RECEIVEPORT = port;
            packet = new byte[256];
            try{
                ds = new DatagramSocket(RECEIVEPORT);
            }catch (SocketException e){
                e.printStackTrace();
            }
        }
 
        @Override
        public void run(){
            dp = new DatagramPacket(packet,packet.length);
            try{
 
                /**
                 * ds的receive方法会阻塞,当读取不到DatagramPacket
                 * 的时候会傻傻地等待!
                 */
                while(true){
                    ds.receive(dp);
                    String value = new String(dp.getData(),0,dp.getLength());
                    print(value);
                }
 
            }catch (IOException e){
                e.printStackTrace();
            }
 
        }
    }
    public static void print(Object o){
        System.out.println(o);
    }
}

Java常用代码示例

BigDecimal工具类封装

package com.scriptwang.Test;
 
import java.math.BigDecimal;
 
/**
 * Created by ScriptWang on 16/11/26.
 *
 *  BigDecimal可用于精!确!计!算!
 */
public class BigDecimalUtil {
 
 
    public static double add(double a1,double a2){
        //将第一个参数转化成字符串构造BigDecimal对象
        BigDecimal a = new BigDecimal(String.valueOf(a1));
 
        //将第二个参数转化成字符串构造BigDecimal对象
        // (注意两次转化字符串的过程不同)
        BigDecimal b = new BigDecimal(Double.toString(a2));
 
        //调用BigDecimal的add方法,在调用doubleValue转换成double类型
        return a.add(b).doubleValue();
    }
 
 
    public static double substract(double a1,double a2){
        BigDecimal a = new BigDecimal(String.valueOf(a1));
        BigDecimal b = new BigDecimal(String.valueOf(a2));
        return a.subtract(b).doubleValue();
    }
 
    public static double multiply(double a1,double a2){
        BigDecimal a = new BigDecimal(String.valueOf(a1));
        BigDecimal b = new BigDecimal(String.valueOf(a2));
        return a.multiply(b).doubleValue();
    }
 
    public static double divide(double a1,double a2){
        BigDecimal a = new BigDecimal(String.valueOf(a1));
        BigDecimal b = new BigDecimal(String.valueOf(a2));
        return a.divide(b).doubleValue();
    }
 
}

对象池的使用示例(多例模式)

package com.scriptwang.Test;
 
import java.util.HashSet;
import java.util.Set;
 
/**
 * Created by ScriptWang on 16/11/26.
 *
 * 对象池的使用示例
 */
public class Dog {
    //加载类的时候初始化一个Set对象池,static的
    private static Set<Dog> dogPool = new HashSet<>();
 
    private String name;
    private int age;
 
    //构造方法私有,不允许别人new对象,只允许自己new对象
    private Dog(String name,int age){
        this.name = name;
        this.age = age;
    }
 
    /**
     *
     * @param name
     * @param age
     * @return Dog
     * 工厂方法,在构造对象的时候,如果对象池里有,就返回已有的对象,不再new
     * 如果没有,则将new的对象加入到对象池中,并将其返回
     */
    public static Dog newInstance(String name,int age){
        //循环对象池
        for (Dog dog : dogPool){
            //比较name和age,如果相同,则返回对象池里已有的对象
            if (dog.getName().equals(name) && dog.getAge() == age){
                return dog;
            }
        }
 
        //如果对象池里没有该对象,则new出新对象加入对象池并返回
        Dog dog = new Dog(name, age);
        dogPool.add(dog);
        return dog;
    }
 
 
 
    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 "Dog : " + name + " : " + age;
    }
}

字符串反转工具类

package com.scriptwang.Test;
 
/**
 * Created by ScriptWang on 16/11/26.
 *
 *  字符串反转工具类
 */
public class StringReverseUtil {
 
    /**
     * @param s
     * @return
     * 递归,用到length和subString方法
     * 从字符串中间掰开,左右互换,一直循环,知道字符串的长度为1返回
     */
    public static String reverse1(String s){
        int len = s.length();
        if (len == 1) return s;
        String left = s.substring(0,len/2);
        String right = s.substring(len/2,len);
        return reverse1(right) + reverse1(left);
    }
 
 
    /**
     *
     * @param s
     * @return
     * 反向循环
     */
    public static String reverse2(String s){
        String ref = "";
        for (int i=s.length() - 1;i >= 0;i--){
            //反向循环字符串连接方法
            ref += s.charAt(i);
        }
        return ref;
    }
 
    /**
     *
     * @param s
     * @return
     * 正向循环
     */
    public static String reverse3(String s){
        char[] chars = s.toCharArray();
        String ref = "";
        for (int i=0;i<chars.length;i++){
            //正向循环字符串连接方法
            ref = chars[i] + ref;
        }
        return ref;
    }
 
    /**
     *
     * @param s
     * @return
     * 用StringBuffer或StrinBuilder的reverse方法
     */
    public static String reverse4(String s){
        StringBuffer sb = new StringBuffer(s);
        return sb.reverse().toString();
    }
}


Set、List和Map遍历方法

package com.scriptwang.Test;
 
import java.util.*;
 
/**
 * Created by ScriptWang on 16/11/26.
 * 循环遍历Set,List和Map的方法:
 * Set和List都可以用Iterator和foreach遍历,List比Set多一种size和get遍历
 * Map有三种遍历方法,分别是keySey ; values ; Map.Entry和entrySet遍历,都使用foreach循环
 */
public class CollectionLoop {
    public static void main(String[] args){
        SetLoop();
        print("=======split line======");
        ListLoop();
        print("========split line=====");
        MapLoop();
    }
 
    public static void print(Object o){
        System.out.println(o);
    }
 
    /**
     * 两种循环方法:foreach循环 ; iterator循环
     */
    public static void SetLoop(){
        Set<String> set = new HashSet<String>();
        for (int i=0;i<4;i++) set.add(""+i);
 
        //foreach loop
        for(String value : set) print(value);
 
        //iterator loop
        for (Iterator<String> i = set.iterator();i.hasNext();){
            String value = i.next();
            print(value);
        }
 
    }
 
 
    /**
     * 三种循环方法:foreach循环 ; iterator循环 ; size get for循环
     */
    public static void ListLoop(){
        List<String> list = new ArrayList<String>();
        for (int i=0;i<4;++i) list.add(""+i);
 
        //foreach loop
        for (String value : list) print(value);
 
        //iterator loop
        for (Iterator<String> i = list.iterator();i.hasNext();){
            String value = i.next();
            print(value);
        }
 
        //size get for loop
        for (int i=0;i<list.size();i++){
            String value = list.get(i);
            print(value);
        }
    }
 
 
    /**
     * 全是用foreach循环
     * 三种循环方法:keySet和get 循环 ; values循环 ; Map.Entry 和entrySet 循环
     */
    public static void MapLoop(){
        Map<String,Integer> map = new TreeMap<String,Integer>();
        for (int i=0;i<4;i++) map.put("key:"+i,i);
 
        //keySet loop
        for (String key : map.keySet()){
            Integer value = map.get(key);
            print(key);
            print(value);
        }
 
        //values loop 缺点:不能循环出key,只能循环出value
        for (Integer value : map.values()){
            print(value);
        }
 
        //Map.Entry和entrySet循环
        for(Map.Entry<String,Integer> entry : map.entrySet()){
            String key = entry.getKey();
            Integer value = entry.getValue();
            print(key);
            print(value);
        }
    }
 
 
}

文件复制

package com.scriptwang.Test;
 
import java.io.*;
 
/**
 * Created by ScriptWang on 16/11/26.
 * 
 */
public class CopyFiles {
    public static void main(String[] args){
        copy("/Volumes/Swap/所有PSD归档.zip","/Volumes/Swap/所有PSD归档1.zip");
    }
 
    public static void copy(String path,String pathout){
 
        InputStream in = null;
        OutputStream out = null;
        byte[] buffer = new byte[256];//准备一个缓冲区
 
        try{
            in = new FileInputStream(path);
            out = new FileOutputStream(pathout);
        }catch (FileNotFoundException e){
            System.out.println("File not found,Please check it!");
        }
        try{
            //将文件读取到buffer里面,并返回读取到字节数!!
            // len是指读取到的字节数
            for (int len = in.read(buffer);len > 0;len = in.read(buffer)){
                System.out.println(len);
                 
                //将buffer从0到len写出去!
                out.write(buffer,0,len);
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }
 
}

序列化与反序列化一个对象

package com.scriptwang.Test;
 
import java.io.Serializable;
 
/**
 * Created by ScriptWang on 16/11/26.
 * 
 * 被序列化的类要实现Serializable接口
 */
public class Student implements Serializable{
    String name;
    int age;
 
    Student(String name,int age){
        this.name = name;
        this.age = age;
    }
 
 
    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
 
 
 
package com.scriptwang.Test;
 
import java.io.*;
 
/**
 * Created by ScriptWang on 16/11/26.
 *
 * 序列化与反序列化一个对象
 */
public class Test4 {
    public static void main(String[] args){
 
        Student s = new Student("A",12);
        serialize("/Volumes/Swap/data.dat",s);
        Student o = (Student) deserialization("/Volumes/Swap/data.dat");
        System.out.println(o);
    }
 
    /**
     *
     * @param path
     * @param obj
     * 序列化一个类
     */
    public static void serialize(String path,Object obj){
        ObjectOutputStream oos = null;
        try{
            //初始化oos
            oos = new ObjectOutputStream(new FileOutputStream(path));
 
            //将obj写到文件
            oos.writeObject(obj);
        }catch(IOException e){
            e.printStackTrace();
        }
 
    }
 
     
    /**
     *
     * @param path
     * @return
     * 反序列化
     */
    public static Object deserialization(String path){
        ObjectInputStream ois = null;
        Object obj = null;
        try{
            //初始化ois
            ois = new ObjectInputStream(new FileInputStream(path));
 
            //从文件读取对象,会抛出ClassNotFoundException
            obj = ois.readObject();
        }catch(IOException | ClassNotFoundException e){
            e.printStackTrace();
        }
 
        return obj;
    }
}

生产者和消费者模型

package com.scriptwang.Test;
 
/**
 * Created by ScriptWang on 16/11/26.
 */
public class ProducerAndCostumer {
    public static void main(String[] agrs){
 
        Stack s = new Stack(4);
 
        //将同一个Stack给Producer和Consumer
        new Thread(new Producer(s)).start();
        //可以同时用两个Producer线程,只要他们总的add和pop的个数相同就不会出现死锁
        new Thread(new Producer(s)).start();
 
        new Thread(new Consumer(s)).start();
    }
}
 
 
class Stack{
    String[] datas;
    int index;
 
    //初始化
    Stack(int capacity){
        datas = new String[capacity];
        index = 0;
    }
 
    /**
     *
     * @param s
     * 添加方法
     */
    public synchronized void add(String s){
        /**
         * 当指针指到栈顶的时候表示Stack已经满了,不能在加了
         * 因此告诉Producer线程们该wait了
         * 等待Consumer来叫醒Producer线程
         */
        while (index == datas.length){
            try{
                this.wait();//等待
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
 
        this.notifyAll();//叫醒正在等待的Comsumer线程
        datas[index] = s;
        index ++;
    }
 
    /**
     *
     * @return
     * 移除方法
     */
    public synchronized String pop(){
        /**
         * 当指针指到栈底时表示Stack已经空了,没有东西可以在pop了
         * 这时需要让Consumer线程wait
         * 让Producer线程叫醒Consumer线程
         */
        while(index == 0){
            try{
                this.wait();//Consumer线程等待
            }catch(InterruptedException e){
                e.printStackTrace();
            }
        }
 
        this.notifyAll();//叫醒Producer线程
        index --;
        return datas[index];
    }
}
 
class Producer implements Runnable{
    private Stack s;
    Producer(Stack s) {
        this.s = s;
    }
 
    @Override
    public void run(){
        for (int i=1;i<=5;i++){//两个Producer线程时,则每个添加五个
            s.add(""+i);
            System.out.println(i + " has add! ^_^ ");
 
        }
    }
}
 
class Consumer implements Runnable{
    private Stack s;
    Consumer(Stack s){
        this.s = s;
    }
 
    @Override
    public void run(){
        for (int i=1;i<=10;++i){//pop10个
            String pop = s.pop();
            System.out.println(pop + " has pop!");
 
            /**
             * pop一个数据后就等待100ms
             * 说明Producer比Consumer快!
             */
            try{
                Thread.sleep(100);
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        }
    }
}

死锁

package com.scriptwang.Test;
 
/**
 * Created by ScriptWang on 16/11/26.
 */
public class DeadLock implements Runnable{
    //flag用于执行不同的代码块
    private boolean flag;
 
    /**
     * 声明o1和o2为static,保证每个DeadLock对象都共享同一份儿o1和o2
     *
     */
    private static Object o1;
    private static Object o2;
 
    // 初始化
    DeadLock(boolean flag){
        this.flag = flag;
 
        //初始化o1和o2
        o1 = new Object();
        o2 = new Object();
    }
 
    public static void main(String[] args){
        new Thread(new DeadLock(false)).start();
        new Thread(new DeadLock(true)).start();
 
    }
 
    @Override
    public void run(){
        //根据flag执行不同的代码块
        if (flag){
            /**
             * 先锁定o1再锁定o2
             */
            synchronized (o1){
                System.out.println("====1");
                try{
                    Thread.sleep(200);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
                synchronized (o2){
                    try{
                        Thread.sleep(200);
                    }catch (InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println("====2");
                }
            }
        } else {
            /**
             * 先锁定o2再锁定o1
             */
            synchronized (o2){
                System.out.println("====3");
                try{
                    Thread.sleep(200);
                }catch(InterruptedException e){
                    e.printStackTrace();
                }
                synchronized (o1){
                    try{
                        Thread.sleep(200);
                    }catch(InterruptedException e){
                        e.printStackTrace();
                    }
                    System.out.println("====4");
                }
            }
        }
    }
 
}

反射(创建对象、访问Field、调用方法、重写toString)

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
 
/**
 * Created by Script Wang on 2016/11/27.
 */
 
class Student {
    private String name;
    private int age;
    Student (){
        name = "";
        age = 0;
    }
    Student (String name,int age){
        this.name = name;
        this.age = age;
    }
 
    public void m(){
        System.out.println("I am invoked ===== !!!");
    }
 
 
    /**
     *
     * @return
     * 利用反射重写toString
     */
    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
 
        Field[] fields = this.getClass().getDeclaredFields();//拿到所有成员变量
 
        //循环成员变量,将变量名值添加到sb中
        for (int i=0;i<fields.length;i++){
            sb.append(fields[i].getName());//拿到当前Field的名字
            sb.append(" = ");//添加等号
            try{
                sb.append(fields[i].get(this));//拿到当前Field的值
            }catch (IllegalAccessException e){
                e.printStackTrace();
            }
 
            //如果遇到最后一个变量,则末尾不添加分号
            if (i != fields.length - 1){
                sb.append(" ; ");
            }
        }
 
        //返回sb的toString
        return sb.toString();
    }
 
}
 
public class TestReflect {
    public static void main(String[] args){
        test1();//打印示例:name = SW ; age = 21
        test2();//打印示例:name = SW ; age = 22
        test3();//打印示例:I am invoked ===== !!!
    }
 
    /**
     * 用反射中的Constructor构建对象
     */
    public static void test1(){
        Class clazz = null;
        Constructor con = null;
        Student s = null;
        try{
            clazz = Class.forName("Student");//抛ClassNotFoundException
            con = clazz.getDeclaredConstructor(String.class,int.class);//抛NoSuchMethodException
            s = (Student) con.newInstance("SW",21);//抛剩下的三个Exception
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (NoSuchMethodException e){
            e.printStackTrace();
        }catch (InstantiationException e){
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }catch (InvocationTargetException e){
            e.printStackTrace();
        }
 
        System.out.println(s);
    }
 
 
 
    /**
     * 用反射为成员变量赋值构建对象(需要被构建对象的类有空的构造方法)
     * 需要知道构造函数需要哪些类型的参数
     *
     */
    public static void test2(){
        Class clazz = null;
        Object obj = null;
        Field[] fields = null;
 
        try{
            clazz = Class.forName("Student");//抛ClassNotFoundException
            obj = clazz.newInstance();//抛剩下的两个Exception
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (InstantiationException e){
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }
 
        //拿到所有Field并循环
        fields = clazz.getDeclaredFields();
        for (Field f : fields){
            f.setAccessible(true);//这句相当重要,可以访问private的变量
            try {
                //get方法会抛IllegalAccessException
                if (f.get(obj) instanceof String){
                    f.set(obj,"SW");//为当前obj 赋值
                } else if (f.get(obj) instanceof Integer){
                    f.set(obj,22);
                }
            }catch (IllegalAccessException e){
                e.printStackTrace();
            }
        }
 
        System.out.println( (Student)obj );
 
    }
 
 
    /**
     * 利用反射调用方法
     */
    public static void test3(){
        Class clazz = null;
        Object obj = null;
        Method[] methods = null;
 
        try{
            clazz = Class.forName("Student");//抛ClassNotFoundException
            obj = clazz.newInstance();//抛剩下的两个Exception
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (InstantiationException e){
            e.printStackTrace();
        }catch (IllegalAccessException e){
            e.printStackTrace();
        }
 
        //拿到所有的Method对象并循环
        methods =clazz.getDeclaredMethods();
        for (Method m : methods){
            if (m.getName().equals("m")){
                m.setAccessible(true);
                try {
                    m.invoke(obj);//调用obj的方法,抛出以下两个Exception
                }catch (IllegalAccessException e){
                    e.printStackTrace();
                } catch (InvocationTargetException e){
                    e.printStackTrace();
                }
 
            }
        }
 
    }
 
 
}

i++ 和 ++i 的区别

i++ 先取值再做自加运算; ++i 先做自加运算在取值.

public class Test{
    public static void main(String[] args){
        int i = 10;
        int i1 = 1 + i++;
        System.out.println(i1);// 11
        System.out.println(i);// 11
        i = 10;
        int i2 = 1 + ++i;
        System.out.println(i2);// 12
        System.out.println(i);// 11
    }
}

JDBC编程示例

package com.scriptwang.test;
 
 
import java.sql.*;
 
/**
 * Created by ScriptWang on 16/11/30.
 * JDBC的基本使用方法
 */
public class TestJDBC {
    public static void main(String[] args){
        Connection c = null;
        Statement s = null;
        PreparedStatement ps = null;
        ResultSet r = null;
        try{
            //1:new驱动程序
            Class.forName("com.mysql.jdbc.Driver");
 
            //2:通过url,username和pwd拿到Connection
            c = DriverManager.getConnection("jdbc:mysql://**","*","*");
 
            //3:通过Conenction创建Statement
            s = c.createStatement();
 
            //4:通过Statement执行sql初始化ResultSet
            r = s.executeQuery("select * from tablename");
 
            //5:对ResultSet进行操作
            while(r.next()){
                String value = r.getString(1);
            }
 
            /**
             * JDBC中比较常用的PreparedStatement的用法
             */
            //通过Connection初始化ps,ps种通过用问号作为占位符
            ps = c.prepareStatement("delete from tablename where id > ?");
            ps.setInt(1,2);//将sql语句种第一个问号设置为2
            int row = ps.executeUpdate();//执行executeUpdate返回受影响的行数
             
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException e){
            e.printStackTrace();
        }finally{
            try{
                if (r != null){
                    r.close();
                    r = null;
                }
                if (ps != null){
                    ps.close();
                    ps = null;
                }
                if (c != null){
                    c.close();
                    c = null;
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
 
    public static void print(Object o){
        System.out.println(o);
    }
}

JDBC事务的使用

package com.scriptwang.test;
 
 
import java.sql.*;
 
/**
 * Created by ScriptWang on 16/11/30.
 * JDBC的事务使用的基本方法
 */
public class TestJDBC {
    public static void main(String[] args){
        Connection c = null;
        Statement s = null;
        PreparedStatement ps = null;
        ResultSet r = null;
        try{
            //1:new驱动程序
            Class.forName("com.mysql.jdbc.Driver");
 
            //2:通过url,username和pwd拿到Connection
            c = DriverManager.getConnection("jdbc:mysql://*","*","*");
 
            //3:将自动提交设置为false
            c.setAutoCommit(false);
 
            //4:通过Conenction创建Statement
            s = c.createStatement();
 
            //5:通过Statement执行sql
            int row = s.executeUpdate("insert into tablename values (2,'B')");
 
            //6:手动提交
            c.commit();
 
            //7:将自动提交还原
            c.setAutoCommit(true);
 
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }catch (SQLException e){
            /**
             * 当以上操作catch到任何的SQLException的时候,需要回滚
             *
             */
            try{
                //1:回滚数据
                c.rollback();
 
                //2:设置自动提交为true
                c.setAutoCommit(true);
                 
            }catch (SQLException e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            try{
                if (r != null){
                    r.close();
                    r = null;
                }
                if (ps != null){
                    ps.close();
                    ps = null;
                }
                if (c != null){
                    c.close();
                    c = null;
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
    }
 
    public static void print(Object o){
        System.out.println(o);
    }
}

JDBC实现数据访问对象层DAO(Data Access Object)

package com.scriptwang.test;
 
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
 
/**
 * Created by ScriptWang on 16/11/30.
 * Dao(Data Access Object)数据访问对象层
 * Dao的设计意图是让上层对待底层数据的时候,能够用一个对象的眼光来看待
 */
public class TestDao {
    public static void main(String[] args){
        List<User> list = new JdbcDao().getAllUsers();
        print(list);
 
    }
 
    public static void print(Object o){
        System.out.println(o);
    }
}
 
 
class User{
    private int id;
    private String name;
    User(int id,String name){
        this.id = id;
        this.name = name;
    }
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public int getId() {
        return id;
    }
 
    public void setId(int id) {
        this.id = id;
    }
 
    @Override
    public String toString(){
        return id + " : " + name;
    }
}
 
class JdbcDao{
 
    /**
     * 静态初始化Driver,无论多少个JdbcDao对象static语句块始终只执行一次
     * 也就是说Driver只初始化一次!!!!
     */
    static {
        try{
            Class.forName("com.mysql.jdbc.Driver");
        }catch (ClassNotFoundException e){
            e.printStackTrace();
        }
    }
 
    /**
     *
     * 拿到连接
     */
    public Connection getConn(){
        Connection c = null;
        String url = "jdbc:mysql://*";
        String user = "*";
        String pwd = "*";
        try{
            c = DriverManager.getConnection(url,user,pwd);
        }catch (SQLException e){
            e.printStackTrace();
        }
        return c;
    }
 
    /**
     * 释放资源
     */
    public void release(ResultSet r , Statement s , Connection c){
 
        try{
            if (r != null){
                r.close();
                r = null;
            }
            if (s!= null){
                s.close();
                s = null;
            }
            if (c != null){
                c.close();
                c = null;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
 
    public void release(Statement s , Connection c){
        try{
            if (s!= null){
                s.close();
                s = null;
            }
            if (c != null){
                c.close();
                c = null;
            }
        }catch (SQLException e){
            e.printStackTrace();
        }
    }
 
    /**
     * 查询所有用户(查)
     */
    public List<User> getAllUsers(){
        List<User> list = new ArrayList<User>();
        Connection c = null;
        Statement s = null;
        ResultSet r = null;
        String sql = "select * from t";
        try{
            c = this.getConn();
            s = c.createStatement();
            r = s.executeQuery(sql);
            while (r.next()){
                User user = new User(r.getInt(1),r.getString(2));
                list.add(user);
            }
            return list;
        }catch (SQLException e){
            e.printStackTrace();
        }finally{
            release(r,s,c);
        }
        return null;
    }
 
 
    /**
     * 根据id获取User对象(查)
     */
    public User getUserById(int id){
        Connection c = null;
        PreparedStatement ps = null;
        ResultSet r = null;
        String sql = "select * from t where id = ?";
        try{
            c = this.getConn();
            ps  = c.prepareStatement(sql);
            ps.setInt(1,id);
            r = ps.executeQuery();
            if (r.next()){
                return new User(r.getInt(1),r.getString(2));
            }
        }catch (SQLException e){
            e.printStackTrace();
        }finally {
            this.release(r,ps,c);
        }
 
        return null;
    }
 
 
    /**
     * 将旧得User改为新的User,返回新的User(改)
     */
    public User updateUser(User oldU,User newU){
        Connection c = null;
        PreparedStatement ps = null;
        String sql = "update t set id = ? ,name = ? where id = ? and name = ?";
        try{
            c = this.getConn();
 
            c.setAutoCommit(false);//事务开始
            ps = c.prepareStatement(sql);
            ps.setInt(1,newU.getId());
            ps.setString(2,newU.getName());
            ps.setInt(3,oldU.getId());
            ps.setString(4,oldU.getName());
            int row = ps.executeUpdate();
            if (row>0){
                c.commit();//提交
                return newU;
            }
        }catch (SQLException e){
            try{
                c.rollback();
                c.setAutoCommit(true);
            }catch (SQLException e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally {
            release(ps,c);
        }
        return null;
    }
 
 
 
    /**
     * 根据id删除用户(删)
     */
    public boolean deleteUserById(int id){
        Connection c = null;
        PreparedStatement ps = null;
        String sql = "delete from t where id = ?";
        int row = 0 ;
        try{
            c = this.getConn();
 
            c.setAutoCommit(false);// 事务开始
 
            ps = c.prepareStatement(sql);
            ps.setInt(1,id);
            row = ps.executeUpdate();//返回受影响的行数,如果没有,返回0
            if (row > 0){
                c.commit();        //提交事务
                return true;
            }
 
        }catch (SQLException e){
            try{
                /**
                 * 如果上面代码catch到Exception
                 * 第一要做的事情是rollback
                 * 第二是将自动提交设置回原来的值
                 */
                c.rollback();
                c.setAutoCommit(true);
            }catch (SQLException e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            System.out.println(row + " rows has delete!");
            this.release(ps,c);
        }
        return false;
    }
 
    /**
     * 插入用户数据(增)
     */
    public boolean insUser(User user){
        Connection c = null;
        PreparedStatement ps = null;
        String sql = "insert into t values (?,?)";
        try{
            c = this.getConn();
 
            c.setAutoCommit(false); //事务开始
 
            ps = c.prepareStatement(sql);
            ps.setInt(1,user.getId());
            ps.setString(2,user.getName());
            int row = ps.executeUpdate();
            if (row > 0){
                c.commit();       //提交
                System.out.println("user"+"("+user.getId()+" : "+user.getName()+")"+" has inserted!");
                return true;
            }
        }catch (SQLException e){
 
            try{
                /**
                 * catch到Exception回滚并还原
                 */
                c.rollback();
                c.setAutoCommit(true);
            }catch (SQLException e1){
                e1.printStackTrace();
            }
            e.printStackTrace();
        }finally{
            release(ps,c);
        }
        return false;
    }
 
}

你可能感兴趣的:(代码狂魔,java)