类加载&反射

#### ClassLoader

- 分类:

1.ApplicationClassLoader  系统加载器

2.ExtensionClassLoader  扩展类加载器

3.BootStrapClassLoader 引导类加载器

- 在JVM中表示两个class对象是否为同一个类对象存在两个必要条件:1.类的完整类名必须一致,包括包名。2.加载这个类的ClassLoader(指ClassLoader实例对象)必须相同。**不同的类加载器加载的同名对象不是同一个Class对象**,但是由于缓存的机制,一般不允许重新加载,除非加载器实现了findClass方法或loadClass方法。

也就是说,在JVM中,即使这个两个类对象(class对象)来源同一个Class文件,被同一个虚拟机所加载,但只要加载它们的ClassLoader实例对象不同,那么这两个类对象也是不相等的,这是因为**不同的ClassLoader实例对象都拥有不同的独立的类名称空间**,‘所以加载的class对象也会存在不同的类名空间中,但前提是覆写loadclass方法。

- 使用:热部署功能时(一个class文件通过不同的类加载器产生不同class对象从而实现热部署功能)

- 代码如何实现双亲委派:

从前面双亲委派模式对loadClass()方法的源码分析中可以知,在方法第一步会通过Class c = findLoadedClass(name);

从缓存查找,类名完整名称相同则不会再次被加载,因此我们必须绕过缓存查询才能重新加载class对象。当然也可直接调用findClass()方法,这样也避免从缓存查找

为类变量(即static修饰的字段变量)分配内存并且设置该类变量的初始值即0(如static int i=5;这里只将i初始化为0,至于5的值将在初始化时赋值),

这里不包含用final修饰的static,因为final在编译的时候就会分配了,

注意这里不会为实例变量分配初始化,类变量会分配在方法区中,而实例变量是会随着对象一起分配到Java堆中。

双亲委派模型的破坏者-线程上下文类加载器。

实际上核心包的SPI类对外部实现类的加载都是基于线程上下文类加载器执行的,通过这种方式实现了Java核心代码内部去调用外部实现类。






public class ClassTest {

public static void main(String[] args) {

/**

* 一个类/j接口/枚举/数组/注解/基础类型/void只有一个类类型(JVM中的.class文件),描述类的类,

* 被加载后,这个类的所有信息都在这个类中

*

*/

        //类加载器

        try {

//获取类的Class-3法

            Class c1 = Class.forName("ReflectionTest.ClassTest");

            Class c2 = ReflectionTest.ClassTest.class;

            Class c3 =new ReflectionTest.ClassTest().getClass();

            System.out.println(c1.hashCode());

            System.out.println(c2.hashCode());

            System.out.println(c3.hashCode());

            Class c4 = Integer.TYPE;

            Class c5 = Comparable.class;

            Class c6 = String[][].class;//所有二维String数组都是一个类类

            Class c7 =Override.class;

            Class c8 = ElementType.class;

            Class c9 = Integer.class;

            Class c11 = Integer.class;

            Class c10 =void.class;//类的类

            Class c12 = String[][].class;

        }catch (ClassNotFoundException e) {

e.printStackTrace();

        }

//类类型

        Person person =new Person();

        person.setAge("15");

        Class aClass = person.getClass();

        System.out.println(aClass.getName());

        try {

//动态加载类dynamic classload e.g. from properties.xml

            Properties properties =new Properties();

            FileInputStream fs =null;

            try {

//                fs = new FileInputStream(new File("pro.properties"));

//                properties.load(fs);

//                String className = properties.getProperty("className");

                Class c = Class.forName("AnotationTest.Person", false, ClassLoader.getSystemClassLoader());

                System.out.println(c.getName());

                Object o = c.newInstance();

                System.out.println(oinstanceof AnotationTest.Person);

                Method method = c.getDeclaredMethod("getAge");

                Method method1 = c.getDeclaredMethod("setName", String.class);//有参,记得指定入参类型

                Object oo = method.invoke(o);

                System.out.println(oo);

            }catch (NoSuchMethodException | InvocationTargetException e) {

e.printStackTrace();

            }

}catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {

e.printStackTrace();

        }

//通过Class获取类的信息(field,method,constructor,annotation,modifier)

//getXX:获取包括父类的public的XX

//getDeclaredXX:获取本类的声明的所有的XX

//private是否accessible,效率高

//生成对象

        Son son1 =new Son("byte");

        Class sonClass = son1.getClass();

        //field

        for (Field field : sonClass.getFields()) {

System.out.println("field:" + field);

        }

for (Field declaredField : sonClass.getDeclaredFields()) {

System.out.println("declaredField" + declaredField);

        }

try {

System.out.println("get field money of Parent:" + sonClass.getField("money"));

            Field field = sonClass.getDeclaredField("name");

            field.setAccessible(true);

            System.out.println("get field name value of son1:" + field.get(son1));

        }catch (NoSuchFieldException e) {

e.printStackTrace();

        }catch (IllegalAccessException e) {

e.printStackTrace();

        }

try {

Method testReflection = sonClass.getMethod("testReflection", List.class, Map.class);

            Type[] parameterTypes = testReflection.getGenericParameterTypes();

            for (Type parameterType : parameterTypes) {

System.out.println("method input parameterType" + parameterType);

                if (parameterTypeinstanceof ParameterizedType) {

for (Type item : ((ParameterizedType) parameterType).getActualTypeArguments()) {

System.out.println("subType of input parameterType " + parameterType +" is :" + item);

                    }

}

}

}catch (NoSuchMethodException e) {

e.printStackTrace();

        }

//method:获取,通过class调用方法

//获取方法参数

        for (Method method : sonClass.getMethods()) {

System.out.println("method:" + method);

        }

for (Method declaredMethod : sonClass.getDeclaredMethods()) {

System.out.println("declaredMethod:" + declaredMethod);

        }

try {

System.out.println("getAge method: " + sonClass.getDeclaredMethod("setAge", int.class));

            System.out.println("setMoney method: " + sonClass.getMethod("setMoney", int.class));//parameterType for overloading

            System.out.println("son1.getMoney:" + son1.getMoney());

            sonClass.getMethod("setMoney", int.class).invoke(son1, 500);

            System.out.println("son1.getMoney:" + son1.getMoney());

        }catch (NoSuchMethodException e) {

e.printStackTrace();

        }catch (IllegalAccessException e) {

e.printStackTrace();

        }catch (InvocationTargetException e) {

e.printStackTrace();

        }

//constructor,生成对象

        try {

Son son = (Son) sonClass.newInstance();//默认调用无参构造函数

            Constructor constructor = sonClass.getConstructor(String.class);

            Son son2 = (Son) constructor.newInstance("son2");

            System.out.println("son2.getName: " + son2.getName());

        }catch (InstantiationException e) {

e.printStackTrace();

        }catch (IllegalAccessException e) {

e.printStackTrace();

        }catch (NoSuchMethodException e) {

e.printStackTrace();

        }catch (InvocationTargetException e) {

e.printStackTrace();

        }

//Annotation,especially over field

    }

}

"https://labuladong.gitbook.io/algo/"

"https://www.acwing.com/solution/leetcode/"

"https://hk029.gitbooks.io/leetbook/twopoint.html"

"https://github.com/CyC2018/CS-Notes/blob/master/notes/Leetcode%20%E9%A2%98%E8%A7%A3%20-%20%E7%9B%AE%E5%BD%95.md"

"https://github.com/youngyangyang04/leetcode-master"

"https://blog.csdn.net/u013850277/article/details/90647636"

"https://www.itcodemonkey.com/article/15510.html"

"https://juejin.im/post/5cccc9d1f265da0384129e5f"

"https://leetcode-cn.com/problems/search-insert-position/solution/te-bie-hao-yong-de-er-fen-cha-fa-fa-mo-ban-python-/"

"https://leetcode-cn.com/problems/find-first-and-last-position-of-element-in-sorted-array/solution/er-fen-cha-zhao-suan-fa-xi-jie-xiang-jie-by-labula/"

"https://blog.csdn.net/yixianfeng41/article/details/55262171" 

"https://blog.csdn.net/yixianfeng41/article/details/52955264"

"https://www.jianshu.com/p/32bcc45efd32" 

"https://www.cnblogs.com/little-YTMM/p/5372680.html" 

"https://blog.csdn.net/weixin_43272781/article/details/82959089" 

"https://www.jianshu.com/p/a0941781926d" 

"https://www.cnblogs.com/xdecode/p/9321848.html" 

"https://www.cnblogs.com/Elliott-Su-Faith-change-our-life/p/7472265.html"

"https://leetcode-cn.com/problems/reverse-linked-list/solution/dong-hua-yan-shi-206-fan-zhuan-lian-biao-by-user74/"

"https://weixin.sogou.com/"

你可能感兴趣的:(类加载&反射)