qq_45100518
倾听雪的声音
2021-05-04 17:35

instanceof 会触发应用程序类加载器吗

《深入理解java虚拟机》中有这样一个实现自己类加载器的代码

public class ClassLoaderTest {
 
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException {
		ClassLoader myLoader = new ClassLoader() {
			@Override
			public Class<?> loadClass(String name) throws ClassNotFoundException {
				try {
					String className = name.substring(name.lastIndexOf(".") + 1) + ".class";
					
					InputStream is = getClass().getResourceAsStream(className);
					if (is == null) return super.loadClass(name);
					byte[] b = new byte[is.available()];
					is.read(b);
					
					return defineClass(name, b, 0, b.length);
				} catch (IOException e) {
					throw new ClassNotFoundException(name);
				}
			}
		};
		
		Object object = myLoader.loadClass("test.ClassLoaderTest").newInstance();
		System.out.println(object.getClass());
		System.out.println(object instanceof test.ClassLoaderTest);
	}
}

最后一行打印是false,书上说是因为加载了两次。请问是instanceof会默认使用应用程序类加载器加载其后的类,然后再做类型比较吗。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

相关推荐