Java 获得Class的绝对路径方法

  Java获得class文件的绝对路径:1.e.g. Foo.class => Foo.class.getResuorce("").getFile();

  该方法在eclipse中或未jar打包时,可以得到,但如果打包的话,会显示Null. (security domain问题);

 2.Foo.clas.getProtectionDomain().getCodeSource().getLocation().getFile()来访问jar中Class文件;

import java.net.URL;
import java.security.CodeSource;
import java.security.ProtectionDomain;

import org.objectweb.asm.ClassWriter;

public class Protection {
    
    public static void main(String args[]) {
        
        String absolutePath = ClassWriter.class.getResource("").getFile();
        /*ProtectionDomain domain = ClassWriter.class.getProtectionDomain();
        if (domain == null)
            return;
        CodeSource codeSource = domain.getCodeSource();
        if (codeSource == null)
            return;
        URL location  = codeSource.getLocation();
        if(location == null)
            return;
        String codeLocation = location.getFile();
        System.out.println(codeLocation);*/
        System.out.println(absolutePath);
    }

}
Exception in thread "main" java.lang.NullPointerException
    at com.sunchao.asm.Protection.main(Protection.java:13)
/F:/51CTO%e4%b8%8b%e8%bd%bd-asm-all-3.0.jar

 

posted @ 2015-05-29 21:35  TomSun*star  阅读(3689)  评论(0编辑  收藏  举报