JDK1.8源码阅读(6)–Error/Exception/Class
一.Error类
类图:
Error类继承于Throwable类
static final long serialVersionUID = 4980196508277280342L; 序列号
public Error()
构造方法,这里用的是父类Throwable的构造方法
public Error() {
super();
}
public Error(String message) 父类的构造方法
public Error(String message) {
//
super(message);
}
public Error(String message, Throwable cause)
public Error(Throwable cause)
protected Error(String message, Throwable cause,
boolean enableSuppression,
boolean writableStackTrace)
可以看到Error类主要的就是4个构造方法,其他的都是使用Throwable类的
二.Exception类
类图:
static final long serialVersionUID = -3387516993124229948L; 序列号
除了四个构造方法外,其他的也一样。
三.Class类
类图:
实现了Type接口,GenericDeclaration接口,AnnotatedElement接口,Serializable接口,首先先看看这几个接口定义了什么:
1️⃣Type接口:
代表Java中的“类型”
主要包括5种实现:Class,TypeVariable,ParameterizedType,WildcardType,GenericArrayType
//返回当前类型的详细介绍
default String getTypeName() {
return toString();
}
2️⃣AnnotatedElement接口,
//判断当前元素上是否存在注解
default boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
return getAnnotation(annotationClass) != null;
}
//返回该元素上指定类型的注解(对于类来说,包括继承来的注解)
<T extends Annotation> T getAnnotation(Class<T> annotationClass)
返回该元素上所有类型的注解(对于类来说,包括继承来的注解)
Annotation[] getAnnotations()
//返回该元素上指定类型的注解(对于类来说,包括继承来的注解)
default <T extends Annotation> T[] getAnnotationsByType(Class<T> annotationClass) {
/*
* Definition of associated: directly or indirectly present OR
* neither directly nor indirectly present AND the element is
* a Class, the annotation type is inheritable, and the
* annotation type is associated with the superclass of the
* element.
*/
T[] result = getDeclaredAnnotationsByType(annotationClass);
if (result.length == 0 && // Neither directly nor indirectly present
this instanceof Class && // the element is a class
AnnotationType.getInstance(annotationClass).isInherited()) { // Inheritable
Class<?> superClass = ((Class<?>) this).getSuperclass();
if (superClass != null) {
// Determine if the annotation is associated with the
// superclass
result = superClass.getAnnotationsByType(annotationClass);
}
}
return result;
}
//返回该元素上指定类型的注解(对于类来说,不包括继承来的注解)
default <T extends Annotation> T getDeclaredAnnotation(Class<T> annotationClass) {
Objects.requireNonNull(annotationClass);
// Loop over all directly-present annotations looking for a matching one
for (Annotation annotation : getDeclaredAnnotations()) {
if (annotationClass.equals(annotation.annotationType())) {
// More robust to do a dynamic cast at runtime instead
// of compile-time only.
return annotationClass.cast(annotation);
}
}
return null;
}
//返回该元素上指定类型的注解(对于类来说,不包括继承来的注解)
default <T extends Annotation> T[] getDeclaredAnnotationsByType(Class<T> annotationClass) {
Objects.requireNonNull(annotationClass);
return AnnotationSupport.
getDirectlyAndIndirectlyPresent(Arrays.stream(getDeclaredAnnotations()).
collect(Collectors.toMap(Annotation::annotationType,
Function.identity(),
((first,second) -> first),
LinkedHashMap::new)),
annotationClass);
}
//返回该元素上所有类型的注解(对于类来说,不包括继承来的注解)
Annotation[] getDeclaredAnnotations();
3️⃣GenericDeclaration接口
泛型元素,指有能力引入泛型声明的元素,比如类、方法、构造器
返回generic type中的type variable,如:Map<K, V>中的K和V
public TypeVariable<?>[] getTypeParameters();
接下来进入Class类的源码分析:
private static final int ANNOTATION= 0x00002000;
private static final int ENUM = 0x00004000;
private static final int SYNTHETIC = 0x00001000;
//可以看做本地方法的注册加载
private static native void registerNatives();
static {
registerNatives();
}
//构造方法,指定类的构造器
private Class(ClassLoader loader) {
classLoader = loader;
}
//重写toString方法,是否是接口,如果是接口输出“interface”;如果不是,判断是否是基本类型,如果是就输出“”,不是输出“class”,最后加个名称
public String toString() {
return (isInterface() ? "interface " : (isPrimitive() ? "" : "class "))
+ getName();
}
//打印类完整声明
public String toGenericString() {
if (isPrimitive()) {
return toString();
} else {
StringBuilder sb = new StringBuilder();
// 加入修饰符
int modifiers = getModifiers() & Modifier.classModifiers();
if (modifiers != 0) {
sb.append(Modifier.toString(modifiers));
sb.append(' ');
}
//加入是否是注解
if (isAnnotation()) {
sb.append('@');
}
//是否是接口
if (isInterface()) { // Note: all annotation types are interfaces
sb.append("interface");
} else {
//是否是枚举类
if (isEnum())
sb.append("enum");
else
sb.append("class");
}
sb.append(' ');
sb.append(getName());
//泛型
TypeVariable<?>[] typeparms = getTypeParameters();
if (typeparms.length > 0) {
boolean first = true;
sb.append('<');
for(TypeVariable<?> typeparm: typeparms) {
if (!first)
sb.append(',');
sb.append(typeparm.getTypeName());
first = false;
}
sb.append('>');
}
return sb.toString();
}
}
//根据类的全名加载类对象,而且加载类之后对类的静态元素进行初始化
@CallerSensitive
public static Class<?> forName(String className)
throws ClassNotFoundException {
Class<?> caller = Reflection.getCallerClass();
return forName0(className, true, ClassLoader.getClassLoader(caller), caller);
}
//根据类的全名和指定的类加载器加载类对象,initialize参数指示是否在加载类之后对类中的静态元素进行初始化
@CallerSensitive
public static Class<?> forName(String name, boolean initialize,
ClassLoader loader)
throws ClassNotFoundException
{
Class<?> caller = null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
// Reflective call to get caller class is only needed if a security manager
// is present. Avoid the overhead of making this call otherwise.
caller = Reflection.getCallerClass();
if (sun.misc.VM.isSystemDomainLoader(loader)) {
ClassLoader ccl = ClassLoader.getClassLoader(caller);
if (!sun.misc.VM.isSystemDomainLoader(ccl)) {
sm.checkPermission(
SecurityConstants.GET_CLASSLOADER_PERMISSION);
}
}
}
return forName0(name, initialize, loader, caller);
}
//本地方法,通过设定类名称,是否初始化静态变量,制定类加载器以及当前调用该方法的类来得到想要的类对象
private static native Class<?> forName0(String name, boolean initialize,
ClassLoader loader,
Class<?> caller)
throws ClassNotFoundException;
//生成当前类的对象
@CallerSensitive
public T newInstance()
throws InstantiationException, IllegalAccessException
{
if (System.getSecurityManager() != null) {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
}
if (cachedConstructor == null) {
if (this == Class.class) {
throw new IllegalAccessException(
"Can not call newInstance() on the Class for java.lang.Class"
);
}
try {
Class<?>[] empty = {};
final Constructor<T> c = getConstructor0(empty, Member.DECLARED);
// Disable accessibility checks on the constructor
// since we have to do the security check here anyway
// (the stack depth is wrong for the Constructor's
// security check to work)
java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Void>() {
public Void run() {
c.setAccessible(true);
return null;
}
});
cachedConstructor = c;
} catch (NoSuchMethodException e) {
throw (InstantiationException)
new InstantiationException(getName()).initCause(e);
}
}
Constructor<T> tmpConstructor = cachedConstructor;
// Security check (same as in java.lang.reflect.Constructor)
int modifiers = tmpConstructor.getModifiers();
if (!Reflection.quickCheckMemberAccess(this, modifiers)) {
Class<?> caller = Reflection.getCallerClass();
if (newInstanceCallerCache != caller) {
Reflection.ensureMemberAccess(caller, this, null, modifiers);
newInstanceCallerCache = caller;
}
}
// Run constructor
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
}
private volatile transient Constructor<T> cachedConstructor; 构造器缓存
private volatile transient Class<?> newInstanceCallerCache; 调用者类的缓存
//本地方法,判断是否是一个对象
public native boolean isInstance(Object obj);
//判断cls是否是当前类的父类
public native boolean isAssignableFrom(Class<?> cls)
//判断是否是个接口
public native boolean isInterface();
public native boolean isArray(); 判断是否是个数组
//判读是否是个基础类型
public native boolean isPrimitive();
//判断是否有注释
public boolean isAnnotation() {
return (getModifiers() & ANNOTATION) != 0;
}
//判断修饰符是否是synthetic
public boolean isSynthetic() {
return (getModifiers() & SYNTHETIC) != 0;
}
//返回类的姓名
public String getName() {
String name = this.name;
if (name == null)
this.name = name = getName0();
return name;
}
private transient String name; 姓名的缓存
private native String getName0(); 获取当前类的名称
//得到当前类所使用的类加载器
@CallerSensitive
public ClassLoader getClassLoader() {
ClassLoader cl = getClassLoader0();
if (cl == null)
return null;
SecurityManager sm = System.getSecurityManager();
if (sm != null) {
ClassLoader.checkClassLoaderPermission(cl, Reflection.getCallerClass());
}
return cl;
}
ClassLoader getClassLoader0() { return classLoader; }
private final ClassLoader classLoader; 类加载器是一个常量,一个类智能指定唯一的类加载器
//返回generic type中的type variable,如:Map<K, V>中的K和V
public TypeVariable<Class<T>>[] getTypeParameters() {
ClassRepository info = getGenericInfo();
if (info != null)
return (TypeVariable<Class<T>>[])info.getTypeParameters();
else
return (TypeVariable<Class<T>>[])new TypeVariable<?>[0];
}
public native Class<? super T> getSuperclass();
本地方法,得到父类
//获取当前类的父类(可识别泛型类型和非泛型类型)
public Type getGenericSuperclass() {
ClassRepository info = getGenericInfo();
if (info == null) {
return getSuperclass();
}
if (isInterface()) {
return null;
}
return info.getSuperclass();
}
//获取当前类所在包的package信息
public Package getPackage() {
return Package.getPackage(this);
}
//获取当前类的父接口,不包括父类/父接口实现的接口(只识别非泛型类型)
public Class<?>[] getInterfaces() {
ReflectionData<T> rd = reflectionData();
if (rd == null) {
// no cloning required
return getInterfaces0();
} else {
Class<?>[] interfaces = rd.interfaces;
if (interfaces == null) {
interfaces = getInterfaces0();
rd.interfaces = interfaces;
}
// defensively copy before handing over to user code
return interfaces.clone();
}
}
private native Class<?>[] getInterfaces0();
//获取当前类的父接口,不包括父类/父接口实现的接口(识别泛型类型)
public Type[] getGenericInterfaces() {
ClassRepository info = getGenericInfo();
return (info == null) ? getInterfaces() : info.getSuperInterfaces();
}
//获取数组的组件类型,如int[]返回int,int[][]返回int[]。如果不是数组,则返回空
public native Class<?> getComponentType();
public native int getModifiers(); //得到修饰符
//获取签名信息
public native Object[] getSigners();
native void setSigners(Object[] signers);
//内部静态类,描述了内部类以及方法名称和方法描述。
private final static class EnclosingMethodInfo {
private Class<?> enclosingClass;
private String name;
private String descriptor;
private EnclosingMethodInfo(Object[] enclosingInfo) {
if (enclosingInfo.length != 3)
throw new InternalError("Malformed enclosing method information");
try {
// The array is expected to have three elements:
// the immediately enclosing class
enclosingClass = (Class<?>) enclosingInfo[0];
assert(enclosingClass != null);
// the immediately enclosing method or constructor's
// name (can be null).
name = (String) enclosingInfo[1];
// the immediately enclosing method or constructor's
// descriptor (null iff name is).
descriptor = (String) enclosingInfo[2];
assert((name != null && descriptor != null) || name == descriptor);
} catch (ClassCastException cce) {
throw new InternalError("Invalid type in enclosing method information", cce);
}
}
boolean isPartial() {
return enclosingClass == null || name == null || descriptor == null;
}
boolean isConstructor() { return !isPartial() && "<init>".equals(name); }
boolean isMethod() { return !isPartial() && !isConstructor() && !"<clinit>".equals(name); }
Class<?> getEnclosingClass() { return enclosingClass; }
String getName() { return name; }
String getDescriptor() { return descriptor; }
}
//得到内部方法明细
private EnclosingMethodInfo getEnclosingMethodInfo() {
Object[] enclosingInfo = getEnclosingMethod0();
if (enclosingInfo == null)
return null;
else {
return new EnclosingMethodInfo(enclosingInfo);
}
}
//得到这个类是在哪个方法中定义的
@CallerSensitive
public Method getEnclosingMethod() throws SecurityException {
EnclosingMethodInfo enclosingInfo = getEnclosingMethodInfo();
if (enclosingInfo == null)
return null;
else {
if (!enclosingInfo.isMethod())
return null;
MethodRepository typeInfo = MethodRepository.make(enclosingInfo.getDescriptor(),
getFactory());
Class<?> returnType = toClass(typeInfo.getReturnType());
Type [] parameterTypes = typeInfo.getParameterTypes();
Class<?>[] parameterClasses = new Class<?>[parameterTypes.length];
// Convert Types to Classes; returned types *should*
// be class objects since the methodDescriptor's used
// don't have generics information
for(int i = 0; i < parameterClasses.length; i++)
parameterClasses[i] = toClass(parameterTypes[i]);
// Perform access check
Class<?> enclosingCandidate = enclosingInfo.getEnclosingClass();
enclosingCandidate.checkMemberAccess(Member.DECLARED,
Reflection.getCallerClass(), true);
/*
* Loop over all declared methods; match method name,
* number of and type of parameters, *and* return
* type. Matching return type is also necessary
* because of covariant returns, etc.
*/
for(Method m: enclosingCandidate.getDeclaredMethods()) {
if (m.getName().equals(enclosingInfo.getName()) ) {
Class<?>[] candidateParamClasses = m.getParameterTypes();
if (candidateParamClasses.length == parameterClasses.length) {
boolean matches = true;
for(int i = 0; i < candidateParamClasses.length; i++) {
if (!candidateParamClasses[i].equals(parameterClasses[i])) {
matches = false;
break;
}
}
if (matches) { // finally, check return type
if (m.getReturnType().equals(returnType) )
return m;
}
}
}
}
throw new InternalError("Enclosing method not found");
}
}
private static Class<?> toClass(Type o) {
if (o instanceof GenericArrayType)
return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
0)
.getClass();
return (Class<?>)o;
}
//如果该类是构造函数中生成的,那么返回这个构造函数
public Constructor<?> getEnclosingConstructor()
//获取[成员内部类]所处的外部类(仅对成员内部类有效),如果并非内部类,则返回null
public Class<?> getDeclaringClass() throws SecurityException
//获取[内部类]所处的外部类(对成员内部类、方法内部类、匿名内部类均有效)
public Class<?> getEnclosingClass() throws SecurityException
// 简单名称,可以看做是不带包名和外部类名的规范名(匿名类没有)
char 基本类型
char[] 基本类型数组
Outer 引用类型
Outer[] 引用类型数组
Inner 内部类
匿名类
Outer$$Lambda$1/1989780873 Lambda表达式
public String getSimpleName()
// 类型名称
char 基本类型
char[] 基本类型数组
com.kang.Outer 引用类型
com.kang.Outer[] 引用类型数组
com.kang.Outer$Inner 内部类
com.kang.Outer$1 匿名类
com.kang.Outer$$Lambda$1/1989780873 Lambda表达式
public String getTypeName()
//判断是否是ascii码
private static boolean isAsciiDigit(char c)
//规范名称,尽量遵从书写习惯(匿名类为null)
char 基本类型
char[] 基本类型数组
com.kang.Outer 引用类型
com.kang.Outer[] 引用类型数组
com.kang.Outer.Inner 内部类
null 匿名类
com.kang.Outer$$Lambda$1/1989780873 Lambda表达式
public String getCanonicalName()
//是不是匿名类
public boolean isAnonymousClass()
//是不是方法内部类
public boolean isLocalClass()
//是不是成员内部类
public boolean isMemberClass()
//返回内部类的名称
private String getSimpleBinaryName()
//是不是方法内部类或者匿名内部类
private boolean isLocalOrAnonymousClass()
// 获取当前类包含的内部类/接口,仅包含public修饰的内部接口、内部抽象类、内部实例类,会继承父类内容,但不会继承父接口的内容
public Class<?>[] getClasses() {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), false);
return java.security.AccessController.doPrivileged(
new java.security.PrivilegedAction<Class<?>[]>() {
public Class<?>[] run() {
List<Class<?>> list = new ArrayList<>();
Class<?> currentClass = Class.this;
while (currentClass != null) {
Class<?>[] members = currentClass.getDeclaredClasses();
for (int i = 0; i < members.length; i++) {
if (Modifier.isPublic(members[i].getModifiers())) {
list.add(members[i]);
}
}
currentClass = currentClass.getSuperclass();
}
return list.toArray(new Class<?>[0]);
}
});
}
// 返回当前类中所有public字段,包括父类/父接口中的public字段
public Field[] getFields() throws SecurityException {
checkMemberAccess(Member.PUBLIC, Reflection.getCallerClass(), true);
return copyFields(privateGetPublicFields(null));
}
public Method[] getMethods() 获取所有public修饰的方法
public Constructor<?>[] getConstructors() 获取所有的public修饰构造函数
public Field getField(String name) 获取指定名称的public修饰的字段
public Method getMethod(String name, Class<?>... parameterTypes) 得到指定名称指定参数的public修饰的方法
public Constructor<T> getConstructor(Class<?>... parameterTypes) 得到指定名称指定参数的public修饰的构造方法
public Class<?>[] getDeclaredClasses() // 获取当前类包含的内部类/接口,包含所有权限修饰符修饰的内部接口、内部抽象类、内部实例类,不会继承父类和父接口的内容
public Field[] getDeclaredFields() 获得所有的字段
public Method[] getDeclaredMethods() 获取所有的方法
public Constructor<?>[] getDeclaredConstructors() 获取所有的构造函数
public Field getDeclaredField(String name) 获取指定名称的字段
public Method getDeclaredMethod(String name, Class<?>... parameterTypes) 获取指定名称和参数的方法
public Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 获取指定名称和参数的构造函数
// /*
* 查找指定名称的资源,并返回其输入流。
* 如果当前类位于命名模块,则在模块路径(根目录)下查找;否则,在类路径(根目录)上查找。
*
* resName路径内部需以"/"分割。
* 如果resName以'/'开头,则会在模块路径/类路径的根目录下查找;
* 如果resName不以'/'开头,则会在(当前类所在目录+"/"+resName)下查找
*/
public InputStream getResourceAsStream(String name)
//查找指定名称的资源,并返回其URL。
public java.net.URL getResource(String name)
//检查类的可访问性
private void checkMemberAccess(int which, Class<?> caller, boolean checkProxyInterfaces) {
final SecurityManager s = System.getSecurityManager();
if (s != null) {
final ClassLoader ccl = ClassLoader.getClassLoader(caller);
final ClassLoader cl = getClassLoader0();
if (which != Member.PUBLIC) {
if (ccl != cl) {
s.checkPermission(SecurityConstants.CHECK_MEMBER_ACCESS_PERMISSION);
}
}
this.checkPackageAccess(ccl, checkProxyInterfaces);
}
}
如果resName以'/'开头,则去掉开头的"/"后返回;否则,将当前类所在包名转换为路径,并将该路径添加到resName前面后返回
private String resolveName(String name)