Contents

Java

class

template

  • template 是 compilation feature, cannot instantiate a template with dynamic class at runtime

enum

  • enum 默认是 String
  • enum.valueOf(str) convert to enum
  • integer enum
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
    public
    enum Type {
      SIGN_CREATE(0), SIGN_CREATE_BONUS(1), HOME_SCREEN(2), REGISTER_SCREEN(3);

      private final int value;

      Type(final int v){value = v;}

    public int getValue() { return value; }
    }
  • 用 index 访问 Type.values()[index]

Project

classpath

  • 访问 resources 也是需要在 classpath 中声明的

Serialize

Gson

  • Gson 应该是还比较好的方案了吧, 没有什么CVE问题

Process

阻塞

  • process 创建时默认重定向到 pipe, 如果主线程不及时读取 pipe 的内容, pipe buffer 会堵塞

format

ConversionArgument CategoryDescription
'b', 'B'generalIf the argument arg is null, then the result is "false". If arg is a boolean or Boolean, then the result is the string returned by String.valueOf(). Otherwise, the result is "true".
'h', 'H'generalIf the argument arg is null, then the result is "null". Otherwise, the result is obtained by invoking Integer.toHexString(arg.hashCode()).
's', 'S'generalIf the argument arg is null, then the result is "null". If arg implements Formattable, then arg.formatTo is invoked. Otherwise, the result is obtained by invoking arg.toString().
'c', 'C'characterThe result is a Unicode character
'd'integralThe result is formatted as a decimal integer
'o'integralThe result is formatted as an octal integer
'x', 'X'integralThe result is formatted as a hexadecimal integer
'e', 'E'floating pointThe result is formatted as a decimal number in computerized scientific notation
'f'floating pointThe result is formatted as a decimal number
'g', 'G'floating pointThe result is formatted using computerized scientific notation or decimal format, depending on the precision and the value after rounding.
'a', 'A'floating pointThe result is formatted as a hexadecimal floating-point number with a significand and an exponent
't', 'T'date/timePrefix for date and time conversion characters. See Date/Time Conversions.
'%'percentThe result is a literal '%' ('\u0025')
'n'line separatorThe result is the platform-specific line separator

date

format

1
2
3
4
5
6
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import org.apache.commons.lang3.time.DurationFormatUtils;

DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
System.out.println(formatter.format(System.currentTimeMillis()));
2022-04-18 20:53:33.000538

duration

1
2
3
4
5
6
import org.apache.commons.lang3.time.DurationFormatUtils;

Long begin = System.currentTimeMillis();
Long end = System.currentTimeMillis();

DurationFormatUtils.formatDuration(end-begin, "HH:mm:ss.SSS")

iterator

iterator and remove

1
2
3
4
5
6
for(Iterator<Map.Entry<String, String>> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry<String, String> entry = it.next();
    if(entry.getKey().equals("")) {
        it.remove();
    }
}

File

Path

  • 一般直接用 Path 处理路径
  • Path.toFile() 直接转 File

join

1
2
3
Path currentPath = Paths.get(System.getProperty("user.dir"));
Path filePath = Paths.get(currentPath.toString(), "data", "foo.txt");
System.out.println(filePath.toString());

list file

1
File[] files = new File("/home").listFiles();

copy&move

move
  • Option

    1. REPLACE_EXISTING
    2. ATOMIC_MOVE
1
Files.move(Paths.get(src), Paths.get(dest), null);
copy
1
Files.copy(Paths.get(src), Paths.get(dest), null);

file exist

1
2
3
4
5
6
7
8
import java.io.File;

public class FileTest {
    public static void main(String args[]) {
      File f = new File("/path/to/file");
      if(f.exists() && f.isFile()) {}
    }
}

Write to File

BufferedWriter 写 String

1
2
3
4
String str = "Hello";
BufferedWriter writer = new BufferedWriter(new FileWriter(fileName));
writer.write(str);
writer.close();

FileOutputStream 写 bytes

1
2
3
4
5
String str = "Hello";
FileOutputStream outputStream = new FileOutputStream(fileName);
byte[] strToBytes = str.getBytes();
outputStream.write(strToBytes);
outputStream.close();

Reflect

from class

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Field[] allFields = Person.class.getDeclaredFields();

assertEquals(2, allFields.length);

assertTrue(Arrays.stream(allFields).anyMatch(field ->
                                             field.getName().equals(LAST_NAME_FIELD)
                                             && field.getType().equals(String.class)));
assertTrue(Arrays.stream(allFields).anyMatch(field ->
                                             field.getName().equals(FIRST_NAME_FIELD)
                                             && field.getType().equals(String.class)));

Object

copy

deep-copy

problem
  • A common solution to the deep copy problem is to use Java Object Serialization (JOS).

Unfortunately, this approach has some problems, too:

  1. It will only work when the object being copied, as well as all of the other objects references directly or indirectly by the object, are serializable. (In other words, they must implement java.io.Serializable.) Fortunately it is often sufficient to simply declare that a given class implements java.io.Serializable and let Java’s default serialization mechanisms do their thing.
  2. Java Object Serialization is slow, and using it to make a deep copy requires both serializing and deserializing. There are ways to speed it up (e.g., by pre-computing serial version ids and defining custom readObject() and writeObject() methods), but this will usually be the primary bottleneck.
  3. The byte array stream implementations included in the java.io package are designed to be general enough to perform reasonable well for data of different sizes and to be safe to use in a multi-threaded environment. These characteristics, however, slow down ByteArrayOutputStream and (to a lesser extent) ByteArrayInputStream.

log

log4j2

dynamic setting

from system property
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
Configutation:
    name: Default
    Properties:
        Property:
            name: logfile
            value: "log"
    Appenders:
        File:
            name: File_Appender
            fileName: ${sys:logfile}
            append: false
            PatternLayout:
                pattern: "%d [%t] %-5level %F:%M:%L: %msg%n%throwable"
1
java -Dlogfile="log4j2.log" main

Disassembly

class

  • Parse class file
1
javap [-c] <class_name>.class
optionsdescription
-cDisassemble the code

jar

  • extract
1
jar xf <jar_file>.jar

java-version

archlinux

1
2
3
archlinux-java status

sudo archlinux-java set <java-environment>(e.g. java-11-openjdk)

Debug

jprofiler