protected final Class<?> findLoadedClass(String name)这个函数怎么用呢??

我想知道一个类是否已经被加载,在网上看见这个方法,但是这个方法声明为

protected final 

我在代码中获得的ClassLoader 是子加载器,子加载器中没有这个方法,我该怎么用到这个方法呢??

代码如下:

public class reflect_private
{
    private String color;
    private void drive(){
        System.out.println("哈哈哈哈哈的颜色为"+color);
    }

}

import java.lang.reflect.Method;

public class reflect_test {
    public static void main(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, NoSuchFieldException {
        ClassLoader cons = Thread.currentThread().getContextClassLoader();
//        Class clazz = Class.forName("reflect_private");//cons.loadClass("reflect_private");
        Class clazz = cons.loadClass("reflect_private");
        reflect_private rp = (reflect_private)clazz.getConstructor().newInstance();
        Field colorfed = clazz.getDeclaredField("color");
        colorfed.setAccessible(true);
        colorfed.set(rp,"red");
        Method driveMd = clazz.getDeclaredMethod("drive",(Class[])null);
        driveMd.setAccessible(true);
        driveMd.invoke(rp,null);
        Method flc = cons.getClass().getDeclaredMethod("findLoadedClass", String.class);
        flc.setAccessible(true);
        flc.invoke(cons,"reflect_private");
    }
}

第二段代码是要运行的代码,报错findLoadedClass方法找不到

最后3行错的,子类的class不包含父类的方法的,必须用父类的class,另外参数必须是全路径:

        Method flc = ClassLoader.class.getDeclaredMethod("findLoadedClass", String.class);
        flc.setAccessible(true);
        Object invoke = flc.invoke(cons, "com.wang.test.JavaMainTest");
        if (invoke != null) {
            System.out.println("已经加载了");
        }

问答版主就是牛,从现在起只回论坛,不在踏入问答半步

把括号中的类名改成类的完整限定名,就是你要获取的reflect_private类在项目中的完整路径,再试一下