1、数据类型转换类
1.1、字节数组转为布尔数组
// 101110101 转为布尔数组static public boolean[] toBitsArray(byte[] bytes, int bitCount) { boolean[] dst = new boolean[bitCount]; for (int i = 0; i < dst.length; i++) { dst[i] = (bytes[i / 8] & (1 << (i % 8))) != 0; } return dst;}
1.2、字节数组转为浮点型
public static float toFloatLittleEndian(byte[] bytes) { return Float.intBitsToFloat( ((bytes[0] & 0xff) << 8) | (bytes[1] & 0xff) | ((bytes[2] & 0xff) << 24) | ((bytes[3] & 0xff) << 16)); } public static float toFloatBigEndian(byte[] bytes) { return Float.intBitsToFloat( ((bytes[0] & 0xff) << 24) | ((bytes[1] & 0xff) << 16) | ((bytes[2] & 0xff) << 8) | ((bytes[3] & 0xff))); } public static float toFloatBigEndianBySwap(byte[] bytes) { return Float.intBitsToFloat( ((bytes[0] & 0xff) << 16) | ((bytes[1] & 0xff) << 24) | (bytes[2] & 0xff) | ((bytes[3] & 0xff) << 8)); } public static float toFloatLittleEndianBySwap(byte[] bytes) { return Float.intBitsToFloat( (bytes[0] & 0xff) | (bytes[1] & 0xff) << 8 | (bytes[2] & 0xff) << 16 | (bytes[3] & 0xff) << 24); }
1.3、字节数组转为整数
//两个字节不带符合public static int byteArrayToInt(byte[] data) { return (data[0] & 255) << 8 | data[1] & 255; }// 两个字节 带符号 public static short byteArrayToShort(byte[] data) { return (short) ((data[0] & 255) << 8 | data[1] & 255); }
2、枚举类示例
public enum FunctionCode { /** * 读线圈状态 */ READ_COIL_STATUS("0x01") { @Override public SimpleModbusRequest buildRequest(int offset, int num) { return new ReadCoilsRequest(offset, num); } }, /** * 未知功能码 */ UNKNOWN("0x00") { @Override public SimpleModbusRequest buildRequest(int offset, int num) { return null; } }; private final String code; public String getCode() { return code; } public static FunctionCode isCode(String code) { Class<FunctionCode> codeClass = FunctionCode.class; FunctionCode functionCode = UNKNOWN; try { for (FunctionCode ele : codeClass.getEnumConstants()) { if (codeClass.getMethod("getCode").invoke(ele).equals(code)) { functionCode = ele; break; } } } catch (Exception e) { e.printStackTrace(); } return functionCode; } FunctionCode(String code) { this.code = code; } public abstract SimpleModbusRequest buildRequest(int offset, int num);}
3、打印进度条
Random random = new Random();for (int i = 0; i <=100 ; i++) { Thread.sleep(random.nextInt(100)); System.out.print("\r"+i+"%");}
4、CompletableFuture
参考
6、Map API
map.computeIfAbsent(key, k -> new ArrayList<>())
7、反射
7.1、给属性赋值,获取值
PropertyDescriptor pd = new PropertyDescriptor(name, cls);Method setMethod = pd.getWriteMethod();setMethod.invoke(object, value);Method getMethod=pd.getReadMethod();getMethod.invoke(object) // apache 工具包 beanutilsBeanUtils.setProperty(ipNetToMediaEntry, name, variable.toString());