前景:最近web项目在实现一个在java文件中读取项目目录webcontent下的某一个资源文件,在static方法中需要获取资源文件的路径,因此需要根据当前的class去获取到webcontent的路径。
众所周知,static修饰的方法中不能使用this关键字,因此不能再static方法中使用this.getClass()获取当前文件的class,因此换一种思路,编写一个静态方法,里面定义一个普通的内部类,在内部类中使用this.getClass(),然后返回,因此在 static方法需要用到当前class的时候,直接调用新编写的static方法即可。如下
public static void main(String[] args){
Class currentClass = getCurrentClass();
}
private static final Class getCurrentClass(){
return new Object(){
public Class getClassForStatic(){
return this.getClass();
}
}.getClassForStatic();
}