zoukankan      html  css  js  c++  java
  • java成神之——ImmutableClass,null检查,字符编码,defaultLogger,可变参数,JavaScriptEngine,2D图,类单例,克隆,修饰符基本操作

    ImmutableClass

    一旦初始化,值无法修改
    主要是用于多线程之间的数据共享,避免数据污染
    
    class不设置setter即可实现Immutable Class
    
    public class ImmutableIntArray {
        private final int[] array;
        public ImmutableIntArray(int[] array) {
            this.array = array.clone();
        }
        public int[] getValue() {
            return this.clone();
        }
    }
    

    null检查

    对象null检查
    Object obj = null;
    Objects.isNull(obj); // true
    Objects.nonNull(obj); // false
    
    集合null检查
    
    List<Object> list = new ArrayList<>();
    list.add(1);
    list.add(2);
    list.add(null);
    list.add(3);
    list.stream().filter(Objects::nonNull).forEach(item -> {
        System.out.println(item);
    }); // 过滤null值
    

    字符编码

    BufferedWriter wr = Files.newBufferedWriter(Paths.get("demo.txt"),StandardCharsets.UTF_8)
    BufferedReader reader = Files.newBufferedReader(Paths.get("demo.txt"),StandardCharsets.UTF_8)
    String s = new String(Files.readAllBytes(Paths.get("demo.txt")), StandardCharsets.UTF_8);
    byte[] bytes = "aaaa".getBytes(StandardCharsets.UTF_8);
    

    default logger

    private static final Logger logger = Logger.getLogger(TestController.class.getName());
    logger.log(Level.INFO, String.format("%s: %s", "输出", "日志"));
    logger.warning(String.format("%s: %s", "输出", "日志"));
    
    日志等级
    SEVERE
    WARNING
    INFO
    CONFIG
    FINE
    FINER
    FINEST
    

    函数可变参数

    void fn(int... x) {
        for (int item : x) {
            System.out.println(item);
        }
    }
    fn(1,2,3,4,5);
    

    Nashorn JavaScript engine

    执行脚本文件

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");
    engine.eval(new FileReader("C:\Users\26401\Desktop\" + "demo.js"));
    

    改变js文件输出流

    ScriptEngineManager manager = new ScriptEngineManager();
    ScriptEngine engine = manager.getEngineByName("nashorn");
    StringWriter stringWriter = new StringWriter();
    engine.getContext().setWriter(stringWriter);
    engine.eval(new FileReader("C:\Users\26401\Desktop\" + "demo.js"));
    return stringWriter.toString();
    

    全局变量

    engine.put("global", "globaldata");
    engine.eval("print(global);");
    
    engine.get("global");
    

    2D图

    package com.springlearn.learn.model;
    import javax.swing.*;
    import java.awt.*;
    // MyPanel extends JPanel, which will eventually be placed in a JFrame
    public class MyPanel extends JPanel {
        // custom painting is performed by the paintComponent method
        @Override
        public void paintComponent(Graphics g){
            // clear the previous painting
            super.paintComponent(g);
            // cast Graphics to Graphics2D
            Graphics2D g2 = (Graphics2D) g;
            g2.setColor(Color.red); // sets Graphics2D color
            // draw the rectangle
            g2.drawRect(0,0,100,100); // drawRect(x-position, y-position, width, height)
            g2.setColor(Color.blue);
            g2.fillRect(200,0,100,100); // fill new rectangle with color blue
        }
    }
    
    public class Test{
        JFrame f;
        MyPanel p;
    
        public Test(){
            f = new JFrame();
            // get the content area of Panel.
            Container c = f.getContentPane();
            // set the LayoutManager
            c.setLayout(new BorderLayout());
            p = new MyPanel();
            // add MyPanel object into container
            c.add(p);
            // set the size of the JFrame
            f.setSize(400,400);
            // make the JFrame visible
            f.setVisible(true);
            // sets close behavior; EXIT_ON_CLOSE invokes System.exit(0) on closing the JFrame
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    
        public static void main(String[] args) throws Exception {
    		DemoApplication t = new DemoApplication(); 
    	}
    }
    

    类单例

    public class Singleton {
        private static final Singleton INSTANCE = new Singleton();
        private Singleton() {}
        public static Singleton getInstance() {
            return INSTANCE;
        }
    }
    
    public class Singleton {
        private static class InstanceHolder {
            static final Singleton INSTANCE = new Singleton();
        }
        public static Singleton getInstance() {
            return InstanceHolder.INSTANCE;
        }
        private Singleton() {}
    }
    

    克隆

    public class Test implements Cloneable {
        @Override
        public Object clone() throws CloneNotSupportedException {
            return super.clone();
        }
    }
    
    Test test = new Test();
    Test testcopy = (Test) test.clone();
    

    修饰符

    常用修饰符
    
        public 公开
        protected 父类和子类可用
        default 不写权限关键字,默认是default,只能在当前package下是使用
        private 本类可用
        final 表示固定不变的
            final修饰的类不能被继承
            final修饰的方法不能被子类重写
            final修饰的变量就是常量,不能修改 final int j = 11;
        static 表示静态,只能通过类本身访问
    
    其他修饰符
    
        strictfp 浮点计算 
            strictfp class A{}
        volatile 多线程中,读取最新值
            volatile boolean active;
        synchronized 只允许一个线程操作
            synchronized void SharedMethod(){}
            void SharedMethod(){
                synchronized (this){
                    ...
                }
            }
        transient 不会被序列化
            public transient int limit = 55; 
    

    结语

    本文章是java成神的系列文章之一
    
    如果你想知道,但是本文没有的,请下方留言
    
    我会第一时间总结出来并发布填充到本文
    
  • 相关阅读:
    执行 composer --version 命令的时候报 Your requirements could not be resolved to an installable set of packages. 错误
    Mac 解决每次新建终端 都要重新运行 source ~/.bash_profile问题
    mac 文件根据权限展示颜色
    Unable to negotiate with 180.101.**.*** port 22: no matching cipher found. Their offer: 3des-cbc,blowfish-cbc,arcfour,cast128-cbc,aes128-cbc,aes192-cbc,aes256-cbc
    带有git账户名称密码更改git推送拉取地址
    使用Java,实现图片与Base64编码互转的程序
    Spring事务管理:ACID的概念,Spring事务管理核心接口,基于XML方式的声明式事务、基于注解(Annotation)方式的声明式事务
    Spring,JDBC, JdbcTemplate的常用方法
    Spring,AOP,基于注解声明式ApsectJ
    养猫记
  • 原文地址:https://www.cnblogs.com/ye-hcj/p/9745810.html
Copyright © 2011-2022 走看看