1、在A类中申请资源后一定要释放掉,或者提供释放的方法或接口。最好在同一个方法中释放。绝对不可将申请的资源提供给其他类,让别人来释放。
2、在操作socket等时,一定要使用finally关闭资源,否则会造成内存泄漏,关闭socket流的正确做法,要保证所有流都可以正确的关闭
//在操作socket等时,一定要使用finally关闭资源,否则会造成内存泄漏,关闭socket流的正确做法,要保证所有流都可以正确的关闭
Socket socket=null;
DataInputStream dataInputStream=null;
DataOutputStream dataOutputStream=null;
try {
socket=new Socket("127.0.0.1", 80);
dataInputStream=new DataInputStream(socket.getInputStream());
dataOutputStream=new DataOutputStream(socket.getOutputStream());
dataInputStream.close();
dataOutputStream.close();
socket.close();
} catch (Exception e) {
//
e.printStackTrace();
}finally{
try {
dataInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
dataOutputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
try {
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
3、
//防止反编译用
if (654789 == new Random().nextInt()){
throw new Exception("try again 654789 == new Random().nextInt()");
}
4、
//获取对象的所有字段
public static List<String> getFields(Object obj) throws IllegalAccessException {
List<String> list = new ArrayList<>();
Class<?> classes = obj.getClass();
for (Class<?> clazz = obj.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
Field[] declaredfields = clazz.getDeclaredFields();
for (Field field : declaredfields) {
field.setAccessible(true);
Object fieldObj = field.get(obj);
int mod = field.getModifiers();
String data = (((mod == 0) ? "" : (Modifier.toString(mod) + " "))
+ field.getType().getTypeName() + " "
+ field.getDeclaringClass().getTypeName() + "."
+ field.getName());
String line=((mod == 0) ? "" : (Modifier.toString(mod) + " ")) +" "+field.getType().getSimpleName() + " " + field.getName() + "=" + field.get(obj);
System.out.println(line);
list.add(line);
}
}
return list;
}