Java进阶笔记

简介

2022/8/22-2022/8/25

常用类

一 包装类
	概述
	装箱与拆箱
	基本类型与字符串之间的转换
二 字符串String类
	String构造函数
	String常用方法
	String类的内存分析
三 可变字符串
四 日期
	Date
	Calendar
	SimpleDateFormat
五 BigDecimal
	为什么使用BigDecimal
六 System
七 对象内存分析

一 包装类

基本类型 == 对应的包装类
装箱 – 拆箱

Byte
Short
Integer
Long
Character
Float
Double
Boolean

装箱 – 拆箱 – 自动装箱拆箱 – 基本类型与字符串之间的转换

    public static void main(String[] args) {
        // 装箱
        Integer integer = new Integer(10);
        Integer integer1 = Integer.valueOf(10);

        // 拆箱
        int i = integer.intValue();
        System.out.println(i);


        // 自动 【装箱 和 拆箱】
        Integer autoVari = 10;


        // 字符串与包装类型的转换
        //      基本类型 --> 字符串        字符串 --> 基本类型
        int tempValue = 10;
        String tempString = tempValue + "";

        int i1 = Integer.parseInt(tempString);
        System.out.println(i1);
    }

二 字符串String类

String类的构造函数

三种构造方式

    public void ConstructStringMethod(){
        // String类的三种构造函数 【char[];byte[]; 构造函数 】
        //  1.1
        String str1 = "123";

        // 1.2
        char[] data1 = {'a','b','c'};
        String str2 = new String(data1);

        // 1.3
        byte[] data = {97,98,99};
        String str3 = new String(data);
    }

常用的方法

    public static void BasicApi(){
        String target = "123456";

        // charAt(Integer index)
        char c = target.charAt(1);

        // contains(String targer)
        boolean contains = target.contains("23");
        System.out.println(contains);

        // endsWith(String suffix)
        boolean b = target.endsWith("56");
        System.out.println(b);

        // startsWith(String prefix)
        boolean b1 = target.startsWith("12");
        System.out.println(b1);

        // equals(String target)
        boolean equals = target.equals("123");
        System.out.println(equals);

        /*
        *   String == > char[]
        *   String ==> byte[]
        * */
        byte[] bytes = target.getBytes(StandardCharsets.UTF_8);
        System.out.println(bytes);

        char[] chars = target.toCharArray();
        System.out.println(chars);

        /*
        *   搜索
        *   indexOf(int ch)
        *   indexOf(int ch,int fromIndex)
        *   lastIndexOf(String str)
        *   lastIndexOf(String str,int fromIndex)
        *
        *   区别:
        *       indexOf()       从左边开始搜索
        *       lastIndexOf()   从右边开始搜索
        * */
        int i = target.indexOf("12");
        System.out.println(i);
        int i1 = target.lastIndexOf("12");
        System.out.println(i1);


        /*
        *   isEmpty()
        *   返回true , 如果且仅当  length() 为0
        * */
        String temp1 = "";
        System.out.println(temp1.isEmpty());

        /*
        *   replace(char oldChar,char newChar)
        * */
        String temp2 = "123abc456";
        temp2.replace("123","!!!");
        System.out.println(temp2);

        /*
        *   String[] splite(String regex)
        * */
        String temp3 = "1,2,3,4,5,6";
        String[] split = temp3.split(",");
        System.out.println(split);

        /*
        *   subString()
        * */
        String temp4 = "123123123123";
        String substring = temp4.substring(3);
        System.out.println(substring);

        /*
        * toLowerCase()
        * toUpperCase()
        * */
        String temp5 = "aaaaaa";
        String s = temp5.toUpperCase(Locale.ROOT);
        System.out.println(s);
        String s1 = s.toLowerCase(Locale.ROOT);
        System.out.println(s1);

        /*
        *   trim()
        * */
        String temp6 = "  123  456   ";
        System.out.println(temp6.trim());
    }

三 可变字符

StringBuilder: 可变长字符串,运行效率快,线程不安全
StringBuffer: 可变长字符串,运行效率慢,线程安全

    public static void VariableStirng(){
        /*
        *   append()
        *   insert()
        *   delete()
        *   replace()
        *   length()
        * */
        StringBuffer temp1 = new StringBuffer();
        StringBuffer append = temp1.append("111").append("222").append("333");
        System.out.println(append);

        System.out.println(append.insert(2, "000000"));

        System.out.println(append.delete(0, 1));

        StringBuffer replace = append.replace(1, 3, "12");
        System.out.println(replace);

        System.out.println(replace.length());
    }

四 日期

Date 对象
Calendar对象
SimpleDateFormat对象
String转Date parse
Date转String format

    public static void method1() throws ParseException {
        // Date
        Date date = new Date();
        long time = date.getTime();
        System.out.println(time);

        // Calendar
        Calendar now = Calendar.getInstance();
        System.out.println(now.get(Calendar.YEAR));


        // Calendar ==> Date
        // String --> Date
        Date dateTime = now.getTime();
        String str = "2022-8-24 10:03:00";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        Date parse = sdf.parse(str);
        System.out.println(parse);

        // Date --> String
        String format = sdf.format(dateTime);
        System.out.println(format);
    }

五 BigDecimal

对于精度要求很高的时候 ==> BigDecimal

    public static void method1(){
        //  对于精度要求很高 ==> BigDecimal
        BigDecimal b1 = new BigDecimal("1.01");
        BigDecimal b2 = new BigDecimal("0.072");

        System.out.println(b1.add(b2));
        System.out.println(b1.subtract(b2));

        System.out.println(b1.multiply(b2));
        System.out.println(b1.divide(b2, 2, BigDecimal.ROUND_FLOOR));
    }

六 System

    public static void method1(){
        int[] array = {1,2,3,4,55};
        int[] target = new int[5];


        System.arraycopy(array,0,target,0,5);
        System.out.println(Arrays.toString(target));

        System.out.println(System.currentTimeMillis());

        System.gc();

        System.exit(0);

        System.out.println("it is over");
    }

泛型与Java集合

一 Collection集合
	集合的概念
	集合框架
	Collection 常用功能
	iterator 迭代器
二 泛型
	泛型的定义
		定义含有泛型的类
		定义含有泛型的方法
		含有泛型的接口
三 集合
	List接口
	List实现类
		ArrayList
		LinkedList
	Set接口
	Set实现类
		HashSet
		TreeSet
	Map接口
	Map实现类
		HashMap
		TreeMap

一 Collection集合

集合的概念

概念: 集合是java中提供的一种容器
数组: 存储一组相同数据类型的数据结构
集合: 动态存放多个对象

集合框架

在这里插入图片描述

    public static void method1(){
        /*
        *   add()
        *   addAll()
        *   clear()
        *   equals()
        *   isEmpty()
        *   remove()
        *   size()
        *   toArray()
        * */
        Collection col = new ArrayList();
        Collection col2 = new ArrayList();
        Collection col3 = new ArrayList();

        col.add(1);
        col.add(2);
        col.add(3);
        col3.add(1);
        col3.add(2);
        col3.add(3);

        col2.add(true);
        col2.add("msg");
        col2.add(new Date());

        col.addAll(col2);
        System.out.println(col);

        col.clear();
        System.out.println(col);

        System.out.println(col.equals(col3));
        System.out.println(col.isEmpty());

        col2.remove(true);
        System.out.println(col2);

        System.out.println(col2.size());
    }

遍历集合: 迭代器

遍历

    public static void method1(){
        Collection col = new ArrayList();

        col.add(1);
        col.add(2);
        col.add(3);

        // 遍历
        for (Object ite:col){
            System.out.println(ite);
        }

        Iterator iterator = col.iterator();

        while(iterator.hasNext()){
            Object next = iterator.next();
            System.out.println(next);
        }
    }

泛型

自动转型

    public static void method1(){
        Collection col = new ArrayList();

        col.add(1);
        col.add(2);
        col.add(3);
        col.add(true);

        Integer sum=0;
        for (Object ite:col){
            if(ite instanceof Integer){
                Integer num = (Integer)ite;
                sum += num;
            }
        }

        System.out.println(sum);
    }

使用泛型定义类

public class Point <T>{
    private T x;
    private T y;

    public Point(T x, T y) {
        this.x = x;
        this.y = y;
    }

    public void setX(T x) {
        this.x = x;
    }

    public void setY(T y) {
        this.y = y;
    }

    // 定义在方法上的泛型
    public static <T> void getValue(T m){
        System.out.println(m);
    }

}

使用通配符定义接口

package com.askelladd.CollectionDemo;

import java.util.List;

/**
 * class description:
 *
 * @Author ludong
 * @Date 2022/8/24 14:21
 * @PackageName:com.askelladd.CollectionDemo
 * @ClassName: Door
 * @Description: TODO
 * @Version 1.0
 */
public interface Door <T>{
    T getType();
}


class Person{}
class Student extends Person{}

class DoorImpl implements Door<String>{
    public String getType() {
        return "Hello";
    }

    // 定义在方法上的泛型
    public static <T> void getValue(T m){
        System.out.println(m);
    }

    // 方法 泛型 通配符
    public static void test1(List<?> list){

    }

    public static void test2(List<Object> list){}

    public static void test3(List<? extends Person> list){}

    public static void test4(List<? super Student> list){}
}

List 接口常用的方法

    public static void method1(){
        /*
        *   add()
        *   get()
        *   remove()
        *   set()
        * */
        List<Integer> list = new ArrayList<>();
        list.add(0,1);
        list.add(2);
        System.out.println(list);
        System.out.println(list.get(1));
        list.remove(1);
        System.out.println(list);
        list.set(0,-1);
        System.out.println(list);
    }

ArrayList & LinkedList

在这里插入图片描述

在这里插入图片描述

Set

HashSet
在这里插入图片描述

TreeSet
有序 + 去重
在这里插入图片描述

Map

在这里插入图片描述在这里插入图片描述

TreeMap

对 key 自动排序
在这里插入图片描述
在这里插入图片描述

集合工具类

Collections

reverse()
shuffle()
sort()
binarySearch()

Java IO流

一 File 类
二 什么是IO
三 IO分类
四 字节流
	字节输出流
		FileOutputStream类
	字节输入流
		FileInputStream类
	综合案例: 图片复制
五 字符流
	字符输入流
		FileReader类
	字符输出流
		FileWriter类
六 缓冲流
	概述
	字节缓冲流
		效率pk
	字符缓冲流
		特有方法
七 转换流
	InputStreamReader类
	OutputStreamWriter类
八 序列化
	概述
	ObjectOutputStream类
		序列化操作
		反序列化操作
九 Properties 属性类

一 File类

概念: 代表物理盘符中的一个文件或者文件夹

在这里插入图片描述

    public static void main(String[] args) throws IOException {
        // iterate all file
        printDir(new File("E:\\dir1"));

    }

    public static void printDir(File dir){
        if(dir.isFile()){
            System.out.println(dir);
        }else{
            File[] files = dir.listFiles();
            for (File ite:files){
                if(dir.isFile()) System.out.println(ite);
                else if(dir.isDirectory())  printDir(ite);
            }

        }
    }

    public static void createFile() throws IOException {
        File file = new File("./1.txt");
        if(!file.exists()){
            file.createNewFile();
        }
    }

    public static void createDirectory(){
        File path = new File("E:\\dir1");
        File path2 = new File("E:\\dir2\\dir3");
        // 创建目录
        if(!path.exists()){
            path.mkdir();
        }
        else{
            path.delete();
        }
        // 创建多级目录
        if(path2.exists()){
            path2.mkdirs();
        }
    }

    public static void getFileInfoList(){
        File path = new File("E:\\dir1");

        String[] list = path.list();
        System.out.println(Arrays.toString(list));

        File[] files = path.listFiles();
        System.out.println(Arrays.toString(files));
    }

IO流

输入流 = 硬盘 到 内存
输出流 = 内存 到 硬盘

字节输入流 InputStream 字节输出流 OutputStream
字符输入流 Reader 字符输出流 Writer

字节输出流

    public static void main(String[] args) throws IOException {
        // 创建字符输出流
        FileOutputStream fos = null;

        try{
            fos = new FileOutputStream("E:\\temp\\temp1\\1.txt",true);
            fos.write(97);
            fos.write(98);
            fos.write(99);

            byte[] bytes = "hello".getBytes(StandardCharsets.UTF_8);
            fos.write(bytes);
        }finally {
            fos.close();
        }

    }

字符输入流

    public static void main(String[] args) throws IOException {
        // 创建流对象
        FileInputStream inputStream = new FileInputStream("E:\\temp\\temp1\\1.txt");
        // 读数据
        char read = (char)inputStream.read();
        System.out.println(read);

        // 一个一个字节读取 while
        int temp;
        while ((temp = inputStream.read()) != -1){
            System.out.println((char) temp);
        }

        // 字符数组读取
        byte[] array = new byte[2];
        int len;

        while((len = inputStream.read(array)) != -1){
            System.out.println(new String(array,0,len));
        }


        inputStream.close();
    }

复制图片案例

    public static void main(String[] args) throws IOException {
        FileInputStream inputStream = new FileInputStream("./1.jpg");
        FileOutputStream fileOutputStream = new FileOutputStream("./2.jpg");

        byte[] buffer = new byte[1024];
        int len;
        while((len = inputStream.read(buffer))!=-1){
            fileOutputStream.write(buffer,0,len);
        }
        
        inputStream.close();
        fileOutputStream.close();
    }

字符输入流

    public static void main(String[] args) throws IOException {
        FileReader fileReader = new FileReader("./1.txt");

        int len;
        char[] buffer = new char[2];
        while((len = fileReader.read(buffer))!=-1){
            System.out.println(new String(buffer,0,len));
        }
        
        fileReader.close();
    }

字符输出流

    public static void main(String[] args) throws IOException {
        FileWriter fileWriter = new FileWriter("./5.txt");

        fileWriter.write('h');
        fileWriter.write('e');

        char[] temp = "llo".toCharArray();
        fileWriter.write(temp);

        fileWriter.write(" world");

        fileWriter.close();
    }

缓冲流

缓冲流也叫高效流

  • 字节缓冲流: BufferedInputStream BufferedOutputStream
  • 字符缓冲流: BufferedReader BufferedWriter

字节缓冲流

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

        BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream("1.jpg"));
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream("3.jpg"));

        int len;
        byte[] bytes = new byte[1024];
        while((len = bufferedInputStream.read(bytes))!=-1){
            bufferedOutputStream.write(bytes);
        }
        bufferedInputStream.close();
        bufferedOutputStream.close();
    }

字符缓冲流

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new FileReader("./1.txt"));
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("./10.txt"));

        String temp = null;
        while((temp = bufferedReader.readLine())!=null){
            System.out.println(temp);
        }


        bufferedWriter.write("hello");
        bufferedWriter.newLine();
        bufferedWriter.write("world");

        bufferedReader.close();
        bufferedWriter.close();
    }

转换流

        InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("1.txt"), "UTF-8");
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(new FileOutputStream("./11.txt"), "UTF-8");

序列化与反序列化

序列化 : 从内存中的对象保存到硬盘上
反序列化 : 从硬盘上将序列化的对象恢复到内存中

public class ObjectStreamDemo {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        TransferObject();
        LoadObject();
    }

    public static void TransferObject() throws IOException {
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("./order.dat"));
        Order order = new Order(1, "2");
        objectOutputStream.writeObject(order);
        objectOutputStream.close();
    }

    public static void LoadObject() throws IOException, ClassNotFoundException {
        ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("./order.dat"));
        Order o = (Order)objectInputStream.readObject();
        System.out.println(o);

        objectInputStream.close();
    }

}

@Data
@AllArgsConstructor
@NoArgsConstructor
class Order implements Serializable {
    private static final long serialVersionUID = 6284260950997027597L;

    private Integer code;
    private String name;
}

Properties属性类

    public static void main(String[] args) throws IOException {
        method1();
    }

    public static void method1() throws IOException {
        Properties properties = new Properties();

        properties.setProperty("key1","value1");
        properties.setProperty("key2","value2");
        System.out.println(properties.getProperty("key1"));

        Set<String> set1 = properties.stringPropertyNames();
        for (String key:set1){
            System.out.println(key+"  "+properties.getProperty(key));
        }

        System.out.println("===================================================");


        properties.load(new FileInputStream("db.properties"));
        Set<String> set2 = properties.stringPropertyNames();
        for (String key:set2){
            System.out.println(key+"  "+properties.getProperty(key));
        }
    }

多线程

并发,并行,进程,线程 概念

并发 两个或多个事件在同一时间段内发生
并行 两个或多个事件在同一时刻发生

进程 系统运行程序的基本单位,线程是进程中的一个执行单元
线程 一个进程中可以包含多个线程

创建线程

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

        MyThread myThread = new MyThread();
        myThread.start();

        for (int i=0;i<20;i++){
            System.out.println("th"+i);
        }

        MyRunnable myRunnable = new MyRunnable();
        Thread thread = new Thread(myRunnable);
        thread.start();

    }
}


class MyThread extends Thread{
    @Override
    public void run() {
        for (int i=0;i<20;i++){
            System.out.println("MyThread:         "+i);
        }
    }
}

class MyRunnable implements Runnable{
    @Override
    public void run() {
        for (int i=0;i<20;i++){
            System.out.println("MyThread2:         "+i);
        }
    }
}

线程的常用的方法

public static void sleep(long mills)
public static void yield()
public final void join()
public void setPriority(int)
public void setDaemon(boolean)

守护线程

守护线程 .setDaemon(true) 设置守护线程
程序中如果所有的前台线程都执行完毕了,后台线程会自动结束
在这里插入图片描述

线程安全

package com.askelladd.ThreadDemo;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * class description:
 *
 * @Author ludong
 * @Date 2022/8/24 23:47
 * @PackageName:com.askelladd.ThreadDemo
 * @ClassName: ThreadSafe
 * @Description: TODO
 * @Version 1.0
 */
public class ThreadSafe {
    public static void main(String[] args) throws InterruptedException {
        Ticket3 ticket = new Ticket3();
        Thread thread = new Thread(ticket);
        Thread thread2 = new Thread(ticket);

        thread.start();
        thread2.start();
    }
}

class Ticket implements Runnable{

    private Integer restNum = 100;

    @Override
    public void run() {

   while(true){
       synchronized (Ticket.class){    // 字节码对象唯一  ; 指定为锁对象
           if(restNum>0){

               try {
                   Thread.sleep(10);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }

               System.out.println("sold the ticket"+restNum--);
           }

       }
   }

    }
}


class Ticket2 implements Runnable{
    private Integer rest = 100;
    private static Integer rest2 = 100;


    @Override
    public void run() {

        while(true){

            if(rest>0){

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                sellTicket();
            }

        }
    }

    public synchronized void sellTicket(){      // lock = this
        System.out.println("sold ticket: "+rest--);
    }

    public synchronized static void sellTicket2(){  // lock = Ticket2.class
        System.out.println("sold ticket: "+rest2--);
    }
}

class Ticket3 implements Runnable{
    private Integer rest = 100;
    Lock lock = new ReentrantLock();


    @Override
    public void run() {

        while(true){
            lock.lock();
            if(rest>0){

                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                sellTicket();
            }.finally{
            	lock.unlock();	// 必须释放锁
            }
            
        }
    }

    public void sellTicket(){      // lock = this
        System.out.println("sold ticket: "+rest--);
    }


}

线程通讯

等待唤醒机制:

public final void wait()
public final void wait(long timeout)
public final void notify()
public final void notifyAll()
public class CoordinateThreadDemo {
    public static void main(String[] args) {
        Object lock = new Object();

        new Thread(()->{
            synchronized (lock){
                System.out.println("1 告诉老板需要什么");
                try {
                    lock.wait(4000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("3 得到老板提供的物品;开始吃饭");
            }

        },"顾客").start();


        new Thread(()->{
            System.out.println("1 告诉老板需要什么");

            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            synchronized (lock){
                System.out.println("2 提供顾客需要的物品");
                lock.notify();
            }

        },"老板").start();
    }
}

死锁

互相占用锁

线程池

线程池的使用demo

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

        // 线程池
        ExecutorService pool = Executors.newFixedThreadPool(3);

        HandleCallable1 t1 = new HandleCallable1("t1");
        HandleCallable1 t2 = new HandleCallable1("t2");
        HandleCallable1 t3 = new HandleCallable1("t3");

        // 提交任务
        Future<Integer> result1 = pool.submit(t1);
        Future<Integer> result2= pool.submit(t2);
        Future<Integer> result3= pool.submit(t3);

        // 关闭线程池
        pool.shutdown();

        // 将 结果打印一下

        try {
            System.out.println(result1.get());
            System.out.println(result2.get());
            System.out.println(result3.get());
        } catch (ExecutionException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


    }
}

class HandleCallable1 implements Callable<Integer>{
    private String name;

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

    @Override
    public Integer call() throws Exception {
        System.out.println(this.name+"开始计算");

        Thread.sleep(200);

        int sum=0;

        Integer temp = (int)(Math.random()*100);
        System.out.println("produce: "+temp);
        for (int i=0;i<temp;i++){
            sum+=i;
        }

        return sum;
    }
}

线程安全集合

CopyOnWriteArrayList

  • 线程安全的ArrayList;加强版 读写分离
  • 写有锁,读无锁,读写之间不阻塞,优于读写锁
  • 写入时,先copy 一个容器副本,再添加新元素,最后替换引用
  • 使用方式与ArrayList无异
public class ThreadSafeCollection {

    public static void main(String[] args) {
        SafeArrayList();
        UnSafeArrayList();
    }

    public static void SafeArrayList(){
        CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>();

        ExecutorService pool = Executors.newFixedThreadPool(5);

        for(int i=0;i<5;i++){
            pool.submit(new Runnable() {
                @Override
                public void run() {

                    for (int j=0;j<10;j++){
                        list.add("content: "+new Random().nextInt(100));
                    }

                }
            });

        }

        pool.shutdown();
        while(!pool.isTerminated()){}

        System.out.println("现在集合的个数  "+list.size());
        for (String ite:list){
            System.out.println(ite);
        }

    }

    public static void UnSafeArrayList(){

        List<String> list = new ArrayList<>();

        ExecutorService pool = Executors.newFixedThreadPool(5);

        for(int i=0;i<5;i++){
            pool.submit(new Runnable() {
                @Override
                public void run() {

                    for (int j=0;j<10;j++){
                        list.add("content: "+new Random().nextInt(100));
                    }

                }
            });

        }

        pool.shutdown();
        while(!pool.isTerminated()){}

        System.out.println("现在集合的个数  "+list.size());
        for (String ite:list){
            System.out.println(ite);
        }

    }
}

CopyOnWriteArraySet
ConcurrentHashMap

枚举&注解&内部类

枚举

概念: 特殊的数据类型,表示一组特定的离散值

package com.askelladd.EnumDemo;

public enum MyFileType {
    TYPE_AUDIO,TYPE_TEXT,TYPE_PICTURE,TYPE_VIDEO
}
@Data
@AllArgsConstructor
@NoArgsConstructor
public class MyFile {

    private int id;
    private String name;
    private MyFileType type;

    public static void main(String[] args) {
        MyFile myFile = new MyFile(1, "2", MyFileType.TYPE_AUDIO);
        System.out.println(myFile);
    }
}

新建枚举类

public enum Sex {
    // 枚举的构造函数不能用 public修饰
    MALE(1,"男性"),FEMALE(2,"男性");

    Sex(int i, String sex_ch) {
    }
}

注解

@Override
@Deprecated :该注解标注的内容,表示已经过时

注解 指定属性列表

public @interface MyAnnotation1 {
    // 1 属性列表的返回值,  必须是一下类型
    // 基本数据类型   String  枚举  注解
    int attr() default 2;
    String attr1();
    Sex attr2();
    String[] attr3();
}

元注解

// @Target: 描述注解能够作用的位置
ElementType.TYPE				指定注解只能修饰类或者接口	--重点
ElementType.FIELD				指定注解只能修饰成员属性	--重点
ElementType.METHOD				指定注解只能修饰方法		--重点
ElementType.PARAMETER			指定注解只能修饰方法的参数
ElementType.CONSTRUCTOR			指定注解只能修饰构造方法
ElementType.LOCAL_VARIABLE		指定注解只能修饰局部变量
ElementType.TYPE_USE			指定注解能修饰所有的

// @Retention:	描述注解呗保留的阶段
RetentionPolicy.SOURCE			注解信息保留在源文件中
RententionPolicy.CLASS			保留在class文件中
RetentionPolicy.RUNTIME			注解i休尼希在运行时保留,搭配反射使用	--重点

反射

概念

反射: 将类的各个组成部分封装为其他对象
好处:
1 可以在程序运行过程中,操作这些对象
2 可以解耦,提高程序的可扩展性

获取Class对象的方式

1 Class.forName(“全类名”); 将字节码文件加载进入内存,返回Class对象
多用于配置文件,将类名定义在配置文件中,读取文件,加载类
2 类名.class: 通过类名的属性class获取
多用于参数的传递
3 对象.getClass(): getClass()方法在Object类中定义着
多用于对象的获取字节码的方式

结论: 同一个字节码文件(*.class) 在一次程序运行过程中,只会被加载一次,不论通过哪一种方式获取的Class对象都是同一个

在这里插入图片描述

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

        Class<?> aClass = Class.forName("com.askelladd.ThreadDemo.Person");

        Class<Person> personClass = Person.class;

        Person person = new Person();
        Class<? extends Person> aClass1 = person.getClass();

        System.out.println(aClass == aClass1);
    }

获取成员变量

获取成员变量

    public static void GetFieldMethod() throws NoSuchFieldException, IllegalAccessException {
        /*
        *   Field[] getFields()                 获取所有public修饰的成员变量
        *   Field getField(String name)         获取指定名称的 public修饰的成员变量
        *   Field[] getDeclaredFields()         获取所有成员变量不考虑修饰符
        *   Field getDeclaredField(String name)
        * */
        Class<Person> personClass = Person.class;
        // getFields()
        Field[] fields = personClass.getFields();
        for (Field field : fields) {
            System.out.println(field);
        }
        //  getDeclaredFields()
        Field[] declaredFields = personClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        System.out.println("\n\n==================================================\n\n");

        //  getField()
        Field name = personClass.getField("rank");
        System.out.println(name);
        //  getDeclaredField()
        Field declaredField = personClass.getDeclaredField("rank");
        System.out.println(declaredField);

        System.out.println("\n\n==================================================\n\n");
        System.out.println("用反射机制   为对象设置值");

        Person person = new Person();
        Field rank = personClass.getField("rank");
        rank.set(person, 123);      // 设置值
        System.out.println(rank.get(person));
        
        Field name1 = personClass.getField("name");
        name1.setAccessible(true);
    }

获取构造函数

    public static void getConstructorMethod() throws NoSuchMethodException, InvocationTargetException, InstantiationException, IllegalAccessException {
        /*
        *   Constructor<?>[] getConstructors()                                  获取所有公共的构造方式
        *   Constructor<T> getConstructor(Class<?>... parameterTypes)
        *   Constructor<T> getDecalaredConstructor(Class<?>... parameterTypes)
        *   Constructor<?>[] getDeclaredConstructors()
        * */
        Class<Person> personClass = Person.class;
        Constructor<?>[] constructors = personClass.getConstructors();
        for (Constructor<?> ite1 : constructors) {
            System.out.println(ite1);
        }

        Constructor<Person> constructor = personClass.getConstructor(Integer.class);
        System.out.println(constructor);

        Constructor<?>[] declaredConstructors = personClass.getDeclaredConstructors();
        for (Constructor<?> ite2 : declaredConstructors) {
            System.out.println(ite2);
        }

        Constructor<Person> declaredConstructor = personClass.getDeclaredConstructor(Integer.class);
        System.out.println(declaredConstructor);


        System.out.println("\n\n==================================================\n\n");
        System.out.println("Constructor 创建对象;即利用反射创建对象");
        Person person = new Person();
        Constructor<Person> constructor1 = personClass.getConstructor(Integer.class);
        Person person1 = constructor1.newInstance(1);
        System.out.println(person1);
    }

获取成员方法

    public static void GetMemberMethod() throws NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        /*
        *   Method[] getMethods()
        *   Method getMethod(String name,Class<?>... parameterTypes)
        *   Method[] getDeclaredMethods()
        *   Method getDeclaredMethod(String name,Class<?>... parameterTypes)
        *  */
        Class<Person> personClass = Person.class;

        Method[] methods = personClass.getMethods();
        for (Method ite : methods) {
            System.out.println(ite);
        }

        Method report = personClass.getMethod("report", Integer.class);
        System.out.println(report);

        // getDeclaredMethods()     getDeclaredMethod()同理
        System.out.println("\n\n==================================================\n\n");
        System.out.println("利用反射调用方法");

        Method report1 = personClass.getMethod("report", Integer.class);
        System.out.println(report1);
        Person person = personClass.newInstance();
        report1.invoke(person,1);
    }

通过反射的方式解析注解的值

    public static void RefelectSetValue() throws NoSuchMethodException {
        Class<TempEntity> tempEntityClass = TempEntity.class;

        // 获取 打在类上的注解   的值
        boolean annotationPresent = tempEntityClass.isAnnotationPresent(MyAnnotation3.class);
        if(annotationPresent){
            MyAnnotation3 annotation = tempEntityClass.getAnnotation(MyAnnotation3.class);
            int age = annotation.age();
            System.out.println(age);
        }

        // 获取   打在方法上   注解的值
        Method eat = tempEntityClass.getMethod("eat");
        boolean annotationPresent1 = eat.isAnnotationPresent(MyAnnotation3.class);
        if (annotationPresent1){
            MyAnnotation3 annotation = eat.getAnnotation(MyAnnotation3.class);
            int age = annotation.age();
            System.out.println(age);
        }
    }

网络编程

概述

OSI参考模型
在这里插入图片描述

网络编程三要素

协议
IP地址
端口号

TCP 编程

概述

TCP通信能实现两台计算机之间的数据交互,通信的两端,要严格区分 客户端 与 服务端

在Java中,提供两个类用于实现TCP通信程序:
1 客户端 java.net.Socket 创建Socket对象,想服务器发送连接请求,服务器响应请求,两者简历连接开始通信
2 服务端 java.net.ServerSocket 创建ServerSocket对象,相当于开启一个服务,并等待客户端的连接

服务器

public class ClientTCP {
    public static void main(String[] args) throws IOException {
        // 创建Socket,连接服务端
        Socket client = new Socket("localhost", 8786);

        // 创建输出流
        OutputStream outputStream = client.getOutputStream();

        // 通过输出流,输出响应的数据
        outputStream.write("你好服务器".getBytes());

        // 通过输入流    获取服务器的数据
        InputStream inputStream = client.getInputStream();
        byte[] buffer = new byte[1024];
        int len = inputStream.read(buffer);
        System.out.println(new String(buffer,0,len));

        // 关闭相关资源
        outputStream.close();
        client.close();
    }
}

客户端

public class ClientTCP {
    public static void main(String[] args) throws IOException {
        // 创建Socket,连接服务端
        Socket client = new Socket("localhost", 8786);

        // 创建输出流
        OutputStream outputStream = client.getOutputStream();

        // 通过输出流,输出响应的数据
        outputStream.write("你好服务器".getBytes());

        // 通过输入流    获取服务器的数据
        InputStream inputStream = client.getInputStream();
        byte[] buffer = new byte[1024];
        int len = inputStream.read(buffer);
        System.out.println(new String(buffer,0,len));

        // 关闭相关资源
        outputStream.close();
        client.close();
    }
}

UDP编程

主要用到了两个类 DatagramPacket 和 DatagramSocket

DatagramSocket

此类表示用来发送和接受数据报包的Socket

DatagramPacket

此类表示数据报包

案例

接受方

public class Client2 {
    public static void main(String[] args) throws IOException {
        // 1
        DatagramSocket receiveSocket = new DatagramSocket(7894);
        // 2 接受数据
        byte[] data = new byte[1024];
        // 3 创建了    数据报 包
        DatagramPacket packet = new DatagramPacket(data, data.length);
        // 4 接受数据
        receiveSocket.receive(packet);
        System.out.println(new String(data,0,packet.getLength()));





        // 指定端口和IP地址
        int port = 7894;
        InetAddress localhost = InetAddress.getByName("localhost");

        byte[] data2 = "hello,UDP".getBytes();
        // 创建数据包
        DatagramPacket packet2 = new DatagramPacket(data2, data2.length, localhost, port);
        // 发送数据
        receiveSocket.send(packet);
        

        // 关闭资源
        receiveSocket.close();
    }
}

发送方

public class Client1 {
    public static void main(String[] args) throws IOException {
        // 发送数据
        System.out.println("Client 启动了");

        // 这个端口是用来接受数据的
        DatagramSocket sendSocket = new DatagramSocket(9999);
        // 指定端口和IP地址
        int port = 7894;
        InetAddress localhost = InetAddress.getByName("localhost");

        byte[] data = "hello,UDP".getBytes();
        // 创建数据包
        DatagramPacket packet = new DatagramPacket(data, data.length, localhost, port);
        // 发送数据
        sendSocket.send(packet);

        // 关闭资源
        sendSocket.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值