Skip to content

Latest commit

 

History

History
89 lines (73 loc) · 2.59 KB

类型信息.md

File metadata and controls

89 lines (73 loc) · 2.59 KB

类型信息

运行时类型

RTTI(RunTime Type information):
  • Class对象

可以表示运行时类型信息,也可以用来创建所有“常规”对象

类的加载:所有的类都是在对其第一使用时,动态加载到JVM中的,当程序创建第一个对类的静态成员的引用时,就会加载这个类。类加载器首先检查这个类的Class对象是否被加载,若没有就根据类名查找.class文件并尝试加载。demo如下:

	class ZhouChaoYuan{
		static{
			System.out.println("loading zhouchaoyuan!");
		}
	}
	class MeiTuan{
		static{
			System.out.println("loading meituan!");
		}
	}
	public class AnyBody{
		public static void main(String[] args){
			new MeiTuan();
			System.out.println("233333333333");
			try{
				Class.forName("ZhouChaoYuan");//查找加载否
			}
			catch(ClassNotFoundException e){
				System.out.println("找不到zhouchaoyuan");
			}
		}
	}
	loading meituan!
	233333333333
	loading zhouchaoyuan!
反射机制:

Class类和java.lang.reflect类库一起对反射概念起了支持。该类库包含Field类,Method类,Constructor类,可以调用getFields(),getMethods(),getConstructors()返回表示字段,方法,以及构造器的对象的数组。demo如下:

    import java.lang.reflect.*;
    import java.util.regex.*;
    public class ShowMethods
    {
    	///匹配所有字母开头,“.”结尾的字符串,如:"java."
    	private static Pattern p=Pattern.compile("\\w+\\.");
    	public static void main(String[] args){
    		if(args.length<1)return;
    		try{
    			Class<?> c=Class.forName(args[0]);
    			Method[] methods=c.getMethods();
    			Constructor[] constructors=c.getConstructors();
    			for(Method method:methods){//将匹配的串替换成空字符串,也就是去掉限定符
    				System.out.println(p.matcher(method.toString()).replaceAll(""));
    			}
    			for(Constructor constructor:constructors){
    				System.out.println(p.matcher(constructor.toString()).replaceAll(""));
    			}
    		}
    		catch(ClassNotFoundException e){
    			;
    		}
    	}
    }

输出如下:

public static void main(String[])
public final void wait() throws InterruptedException
public final void wait(long,int) throws InterruptedException
public final native void wait(long) throws InterruptedException
public boolean equals(Object)
public String toString()
public native int hashCode()
public final native Class getClass()
public final native void notify()
public final native void notifyAll()
public ShowMethods()