预防空指针的方法

public static T validateNullPointer(T object) {
//FILE_LINE_FUNC(),获取validateNullPointer()调用点的文件名、行号、方法名信息
if (object == null) {
throw new NullPointerException(FILE_LINE_FUNC()
+ "NullPointerException");
}
return object;

}

在“.”语句时

Debug.validateNullPointer(crashPath).exists();


关键在FILE_LINE_FUNC()方法:

下面贴出完整源代码:

package com.zjg.youhuodong;


import java.text.SimpleDateFormat;
import java.util.Date;


public final class Debug {


private Debug() {
// TODO 自动生成的构造函数存根
}


private static StackTraceElement getStackTraceElement(int level) {
StackTraceElement[] traceElement = (new Exception()).getStackTrace();
level = Math.min(Math.max(level, 2), traceElement.length - 1);
return ((new Exception()).getStackTrace())[level];
}


public static final int THROW_PLACE = 2;
public static final int ONE_LEVEL_CALL_PLACE = 3;


public static T validateNullPointer(T object) {
//FILE_LINE_FUNC(),获取validateNullPointer()调用点的文件名、行号、方法名信息
if (object == null) {
throw new NullPointerException(FILE_LINE_FUNC()
+ "NullPointerException");
}
return object;
}


public static String FILE_LINE_FUNC(int level) {
StackTraceElement traceElement = getStackTraceElement(level);
return new StringBuffer("[").append("FILE:")
.append(traceElement.getFileName()).append("|").append("LINE:")
.append(traceElement.getLineNumber()).append("|")
.append("FUNC:").append(traceElement.getMethodName())
.append("]").toString();
}


public static String FILE_LINE_FUNC() {
StackTraceElement traceElement = getStackTraceElement(ONE_LEVEL_CALL_PLACE);
return new StringBuffer("[").append("FILE:")
.append(traceElement.getFileName()).append("|").append("LINE:")
.append(traceElement.getLineNumber()).append("|")
.append("FUNC:").append(traceElement.getMethodName())
.append("]").toString();
}


public static String CLASS(int level) {
return getStackTraceElement(level).getClassName();
}


public static String CLASS() {
return getStackTraceElement(ONE_LEVEL_CALL_PLACE).getClassName();
}


public static String FILE(int level) {
return getStackTraceElement(level).getFileName();
}


public static String FILE() {
return getStackTraceElement(ONE_LEVEL_CALL_PLACE).getFileName();
}


public static String FUNC(int level) {
return getStackTraceElement(level).getMethodName();
}


public static String FUNC() {
return getStackTraceElement(ONE_LEVEL_CALL_PLACE).getMethodName();
}


public static int LINE(int level) {
return getStackTraceElement(level).getLineNumber();
}


public static int LINE() {
return getStackTraceElement(ONE_LEVEL_CALL_PLACE).getLineNumber();
}


public static String TIME() {
return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS")
.format(new Date());
}
}


不知还有没有更好的方法?

你可能感兴趣的:(java)