Class对象

1、反射

1.Class.forName("")
根据给定字符串加载类。
2.newInstance()
创建由class表示的类实例对象
3.getMethods()
返回所有的公共方法,包含父类
4.getDeclaredMethods()
返回类或接口的声明方法包括public, protected, default (package),不包含继承方法
5.method.invoke(obj,args)
执行方法,需要传入执行对象及参数。
执行私有方法需要设置method.setAccessible(true);
6.getClassLoader()
获取classLoader BootstrapLoader->ExtClassLoader->AppClassLoader

public class TestClass {
    public TestClass() {
        System.out.println("init TestClass");
    }

    private void myPrivateMethod(){
        System.out.println("this is a private method");
    }

    public void myPublicMethod(){
        System.out.println("this is a public method");
    }
}


public class ClassTest {

    @Test
    public void testClassLoader(){
        ClassLoader classLoader = Test.class.getClassLoader();
        System.out.println(classLoader);

        ClassLoader classLoader1 = classLoader.getParent();
        System.out.println(classLoader1);

        ClassLoader classLoader2 = classLoader1.getParent();
        System.out.println(classLoader2);
    }

    @Test
    public void testInstance() throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException {
        Class s = (Class) Class.forName("TestClass");
        TestClass testInstance = s.newInstance() ;
        for(Method method: s.getMethods()){
            System.out.println(method);
        }

        System.out.println("\n");
        for(Method method: s.getDeclaredMethods()){
            System.out.println(method);
            method.setAccessible(true);
            method.invoke(testInstance,null) ;
        }
    }
}

//输出信息
sun.misc.Launcher$AppClassLoader@18b4aac2
sun.misc.Launcher$ExtClassLoader@452b3a41
null

init TestClass
public void TestClass.myPublicMethod()
public final void java.lang.Object.wait() throws java.lang.InterruptedException
public final void java.lang.Object.wait(long,int) throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long) throws java.lang.InterruptedException
public boolean java.lang.Object.equals(java.lang.Object)
public java.lang.String java.lang.Object.toString()
public native int java.lang.Object.hashCode()
public final native java.lang.Class java.lang.Object.getClass()
public final native void java.lang.Object.notify()
public final native void java.lang.Object.notifyAll()


private void TestClass.myPrivateMethod()
this is a private method
public void TestClass.myPublicMethod()
this is a public method

你可能感兴趣的:(Class对象)