`
Flory
  • 浏览: 23512 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

关于getClass().getClassLoader()

 
阅读更多

关于getClass().getClassLoader()

InputStream is = getClass().getClassLoader().getResourceAsStream("helloworld.properties");中getClass()和getClassLoader()都是什么意思呀.
getClass():取得当前对象所属的Class对象
getClassLoader():取得该Class对象的类装载器
类装载器负责从Java字符文件将字符流读入内存,并构造Class类对象,在你说的问题哪里,通过它可以得到一个文件的输入流
getClass :
public final Class getClass()
Returns the runtime class of an object. That Class object is the object that is locked by static synchronized methods of the represented class.
Returns:
the object of type Class that represents the runtime class of the object.


getClassLoader
public ClassLoader getClassLoader()
Returns the class loader for the class. Some implementations may use null to represent the bootstrap class loader. This method will return null in such implementations if this class was loaded by the bootstrap class loader.
If a security manager is present, and the caller´s class loader is not null and the caller´s class loader is not the same as or an ancestor of the class loader for the class whose class loader is requested, then this method calls the security manager´s checkPermission method with a RuntimePermission("getClassLoader") permission to ensure it´s ok to access the class loader for the class.

If this object represents a primitive type or void, null is returned.

Returns:
the class loader that loaded the class or interface represented by this object.
Throws:
SecurityException - if a security manager exists and its checkPermission method denies access to the class loader for the class.
See Also:
ClassLoader, SecurityManager.checkPermission(java.security.Permission), RuntimePermission

Class.getClassLoader()的一个小陷阱:)
昨天我的code总在Integer.class.getClassLoader().getResource("*********");这一句抛出空指针异常,定位为getClassLoader()返回null,查了一下jdk的文档,原来这里还有一个陷阱:
jdk中关于getClassLoader()的描述:
/**
* Returns the class loader for the class. Some implementations may use
* null to represent the bootstrap class loader. This method will return
* null in such implementations if this class was loaded by the bootstrap
* class loader.
*
* <p> If a security manager is present, and the caller's class loader is
* not null and the caller's class loader is not the same as or an ancestor of
* the class loader for the class whose class loader is requested, then
* this method calls the security manager's <code>checkPermission</code>
* method with a <code>RuntimePermission("getClassLoader")</code>
* permission to ensure it's ok to access the class loader for the class.
*
* <p>If this object
* represents a primitive type or void, null is returned.
.....

上面的英文可以用下面的话来理解:

装载类的过程非常简单:查找类所在位置,并将找到的Java类的字节码装入内存,生成对应的Class对象。Java的类装载器专门用来实现这样的过程,JVM并不止有一个类装载器,事实上,如果你愿意的话,你可以让JVM拥有无数个类装载器,当然这除了测试JVM外,我想不出还有其他的用途。你应该已经发现到了这样一个问题,类装载器自身也是一个类,它也需要被装载到内存中来,那么这些类装载器由谁来装载呢,总得有个根吧?没错,确实存在这样的根,它就是神龙见首不见尾的Bootstrap ClassLoader. 为什么说它神龙见首不见尾呢,因为你根本无法在Java代码中抓住哪怕是它的一点点的尾巴,尽管你能时时刻刻体会到它的存在,因为java的运行环境所需要的所有类库,都由它来装载,而它本身是C++写的程序,可以独立运行,可以说是JVM的运行起点,伟大吧。在Bootstrap完成它的任务后,会生成一个AppClassLoader(实际上之前系统还会使用扩展类装载器ExtClassLoader,它用于装载Java运行环境扩展包中的类),这个类装载器才是我们经常使用的,可以调用ClassLoader.getSystemClassLoader() 来获得,我们假定程序中没有使用类装载器相关操作设定或者自定义新的类装载器,那么我们编写的所有java类通通会由它来装载,值得尊敬吧。AppClassLoader查找类的区域就是耳熟能详的Classpath,也是初学者必须跨过的门槛,有没有灵光一闪的感觉,我们按照它的类查找范围给它取名为类路径类装载器。还是先前假定的情况,当Java中出现新的类,AppClassLoader首先在类传递给它的父类类装载器,也就是Extion ClassLoader,询问它是否能够装载该类,如果能,那AppClassLoader就不干这活了,同样Extion ClassLoader在装载时,也会先问问它的父类装载器。我们可以看出类装载器实际上是一个树状的结构图,每个类装载器有自己的父亲,类装载器在装载类时,总是先让自己的父类装载器装载(多么尊敬长辈),如果父类装载器无法装载该类时,自己就会动手装载,如果它也装载不了,那么对不起,它会大喊一声:Exception,class not found。有必要提一句,当由直接使用类路径装载器装载类失败抛出的是NoClassDefFoundException异常。如果使用自定义的类装载器loadClass方法或者ClassLoader的findSystemClass方法装载类,如果你不去刻意改变,那么抛出的是ClassNotFoundException。

这里jdk告诉我们:如果一个类是通过bootstrap 载入的,那我们通过这个类去获得classloader的话,有些jdk的实现是会返回一个null的,比如说我用 new Object().getClass().getClassLoader()的话,会返回一个null,这样的话上面的代码就会出现NullPointer异常.所以保险起见我们最好还是使用我们自己写的类来获取classloader("this.getClass().getClassLoader()“),这样一来就不会有问题。

分享到:
评论

相关推荐

    Java 使用getClass().getResourceAsStream()方法获取资源

    主要介绍了Java 使用getClass().getResourceAsStream()方法获取资源的相关资料,这里主要讲解哪种方式可以获取到文件资源,需要的朋友可以参考下

    Java ClassLoader学习总结

    主要内容包括 Java类加载机制及加载流程,以及如何定义自己的类加载器,如何实现类的热替换。

    调用webservice例子 查询手机号归属地 soap协议的传xml

    InputStream inStream = this.getClass().getClassLoader().getResourceAsStream("mobilesoap.xml"); try { addressView.setText(MobileInfoService.getMobileAddress(inStream, mobile)); } catch...

    java类读取配置文件信息

    在java类里直接读取配置文件中的信息,用到的方法是this.getClass().getClassLoader().getResourceAsStream

    Activiti modeler 设计器汉化文件

    Activiti modeler 设计器汉化文件。引入方式:修改StencilsetRestResource中的InputStream stencilsetStream = this.getClass().getClassLoader().getResourceAsStream("stencilset.json.zh-cn");

    java工厂系列设计模式源码与文档

    Document document = sb.build(this.getClass().getClassLoader().getResourceAsStream(fileName)); Element root = document.getRootElement(); List list = XPath.selectNodes(root, "/beans/bean"); for...

    Spring原理模拟代码

    Document doc = sb.build(this.getClass().getClassLoader() .getResourceAsStream("beans.xml")); Element root = doc.getRootElement();// 获取根元素 List&lt;?&gt; list = root.getChildren("bean");// 获取...

    Java 高级特性.doc

    //System.out.println(ProxyTest.class.getClassLoader().getParent().getClass().getName()); System.out.println(ProxyTest.class.getClassLoader().getClass().getName()); //test1(); //test2(); } ...

    测试 test-spring-spi

    List&lt;Say&gt; loadFactories = SpringFactoriesLoader.loadFactories(Say.class, TestCase.class.getClassLoader()); for (int i = 0; i &lt; loadFactories.size(); i++) { Say say = loadFactories.get(i); ...

    MvpDemo:开发模式MVP

    mProxyView = (V) Proxy.newProxyInstance(view.getClass().getClassLoader(), view.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, ...

    Java获取*路径实现探讨

    (1)、request.getRealPath(“/”);//不推荐使用获取工程的根路径 (2)、...//获取工程的根路径,这个方法比较好用,可以直接在servlet和jsp中使用 (4)、 this.getClass().getClassLoader().getResource(“”).getPath();

    java 实现AOP

     businessImp.getClass().getClassLoader(),  businessImp.getClass().getInterfaces(),  handler); proxy.processBusiness(); BusinessInterface businessImp = new BusinessObject(); ...

    librec:更改librec(https

    librec 这个项目是一个分支,我为自己的研究见解做了一些改进。由Maven管理对于我来说,我更喜欢使用maven和Idea Intellij ,而maven是一个面向项目的... getClass() . getClassLoader() . getResourceAsStream(conf);

    c3p0工具包(jdbc)

    chain.doFilter((ServletRequest) Proxy.newProxyInstance(CharFilter.class.getClassLoader(),request.getClass().getInterfaces(), new InvocationHandler(){ public Object invoke(Object proxy, Method ...

    android-studio-unit-test-resource-issue-demo:演示执行单元测试时缺少Java资源的问题

    InputStream is = getClass() . getClassLoader() . getResourceAsStream( " path/to/resource.txt " ); 此问题影响非Android单元测试和Java资源,仅在具有“单元测试”配置的Android Studio上执行。 它不影响使用...

    经典java小程序源代码合集.zip

    ClassLoader cl = this.getClass().getClassLoader(); Toolkit tk = Toolkit.getDefaultToolkit(); int length=14, game_state, winner, check, step; int grid[][] = new int[length][length]; int locX...

    带注释的Bootstrap.java

    commonLoader=this.getClass().getClassLoader(); } //创建catalinaLoader、sharedLoader catalinaLoader = createClassLoader("server", commonLoader); sharedLoader = createClassLoader("shared", ...

    大数据面试题.pdf

    反射有三种获取的⽅式,分别是:forName / getClass / 直接使⽤class⽅式 使⽤反射可以获取类的实例 1-6)列出⾄少五种设计模式 设计⽅式有⼯⼚法,懒加载,观察者模式,静态⼯⼚,迭代器模式,外观模式、、、、 1-...

    Java编程经验

    调用new A().getClass().getClassLoader().toString() 打印出来就可以看到,把class文件放在不同的路径下再次执行,就会看到区别。特别注意的是如果打印出来是null就表示到了最高级 BootClassLoader, 因为它是C++...

    Socket聊天室源程序

    Socket聊天室源程序 import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import java.io.*;...public class ChatClient extends JFrame implements ActionListener{ ...

Global site tag (gtag.js) - Google Analytics