码迷,mamicode.com
首页 > 编程语言 > 详细

Java Class对象

时间:2021-03-08 13:49:09      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:alc   oid   http   exce   private   image   eric   图片   ons   

一、获取Class对象的三种方式

1. 运用.class的方式来获取Class实例,对于基本数据类型的封装类,还可以采运用.class的方式来获取Class实例,对于基本数据类型的封装类,还可以采用.TYPE来获取相对应的基本数据类型的Class实例。

2. 利用对象调用getClass方法获取该对象的Class实例。

3. 使用Class类的静态方法forName,用类的名字获取一个Class实例。

package ch15;

public class ClassTest {
    public static void main(String[] args) throws ClassNotFoundException {
        Integer in = 5;
        Class c1 = int.class;
        System.out.println("c1 = " + c1);

        Class c2 = Integer.class;
        System.out.println("c2 = " + c2);

        Class c3 = Integer.TYPE;
        System.out.println("c3 = " + c3);

        Class c4 = in.getClass();
        System.out.println("c4 = " + c4);

        Class<?> c5 = Class.forName("java.lang.String");
        System.out.println("c5 = " + c5);

        Class c6 = Student.class;
        System.out.println("c6 = " + c6);

        Class<?> c7 = Class.forName("ch15.Student");
        System.out.println("c7 = " + c7);
    }
}

class Student {
    static {
        System.out.println("加载Student类");
    }

    public Student() {
        System.out.println("Construct Student");
    }
}

二、获取类型信息

package ch15;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

class MyClass {
    public int pubField;
    protected int proField;
    private int priField;

    public MyClass() {}

    public MyClass(int a) {}

    protected MyClass(int a, int b) {}

    private MyClass(int a, int b, int c) {}

    public void pub_method() {}

    protected void pro_method() {}

    void defMethod() {}
    private void priMethod() {}
    public static void staticMethod() {}
}

interface MyInterface{
    float pi = 3.14f;
    void fun();
    default void defFun() {}
    static void staticFun() {}
    void priFun();
}

public class ClassInfo{
    public static void main(String[] args) {
        Class clz = MyClass.class;
        System.out.println("Fields:");
        // 只获取公共字段
        for (Field f:clz.getFields()){
            System.out.println(f);
        }

        System.out.println("----------------------------------");

        System.out.println("Constructors:");
        // 获取所有声明的构造器
        for (Constructor c:clz.getDeclaredConstructors()){
            System.out.println(c);
        }

        System.out.println("----------------------------------");

        System.out.println("Methods:");
        // 只获取公共方法,包括从Object继承的公共方法
        for (Method m : clz.getMethods()){
            System.out.println(m);
        }

        System.out.println("----------------------------------");

        clz = MyInterface.class;
        System.out.println("Interface‘s Methods:");
        // 只获取接口中的公共方法
        for (Method m : clz.getMethods()){
            System.out.println(m);
        }

    }
}

技术图片

二、获取基类和接口信息

package ch15;

interface A {
}

interface B {
}

class Base {
}

class Derived extends Base implements A, B {
}

public class SuperClassAndInterface {
    public static void main(String[] args) {
        Class clz = Derived.class;
        Class baseClz = clz.getSuperclass();
        System.out.println("基类:");
        System.out.println(baseClz);

        System.out.println("实现的接口:");
        Class[] interfaces = clz.getInterfaces();
        for (Class c : interfaces) {
            System.out.println(c);
        }
    }
}

技术图片

三、获取枚举信息

如果Class对象表示的是枚举类型,那么可以调用 getEnumConstants方法来得到所有的枚举值。

package ch15;

enum Week {
    Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday;
}

public class EnumInfo {
    public static void main(String[] args) {
        Class<Week> clz = Week.class;

        Week[] weeks = clz.getEnumConstants();
        for (Week w : weeks) {
            System.out.println(w);
        }
    }
}

技术图片

四、获取泛型信息

package ch15;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;

interface Functor<T> {
    void call(T args);
}

class MyCallBack implements Functor<Object> {

    @Override
    public void call(Object args) {
        System.out.println(args);
    }
}

class CallbackTest {
    public static <T> T callback(ArrayList<T> list, Functor<? super T> fun) {
        for (T each : list) {
            fun.call(each);
        }
        return list.get(0);
    }
}

public class GenericInfo {
    public static void main(String[] args) {
        System.out.println("[MyCallBack类的泛型信息]");
        Class clz = MyCallBack.class;
        Type baseType = clz.getGenericSuperclass();
        System.out.println("基类:");
        System.out.println(baseType);

        System.out.println("实现的接口:");
        Type[] interfaces = clz.getGenericInterfaces();
        for (Type t : interfaces) {
            System.out.println(t);
            // 如果接口是参数化类型
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) t;
                //得到实际的类型参数
                Type[] typeArgs = pt.getActualTypeArguments();
                for (Type ta : typeArgs) {
                    System.out.println("--实际的类型参数:" + ta);
                }
            }
        }
    }
}

技术图片

package ch15;

import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.WildcardType;
import java.util.ArrayList;
import java.util.Arrays;

interface Functor<T> {
    void call(T args);
}

class MyCallBack implements Functor<Object> {

    @Override
    public void call(Object args) {
        System.out.println(args);
    }
}

class CallbackTest {
    public static <T> T callback(ArrayList<T> list, Functor<? super T> fun) {
        for (T each : list) {
            fun.call(each);
        }
        return list.get(0);
    }
}

public class GenericInfo {
    public static void main(String[] args) {
        System.out.println("[MyCallBack类的泛型信息]");
        Class clz = MyCallBack.class;
        Type baseType = clz.getGenericSuperclass();
        System.out.println("基类:");
        System.out.println(baseType);

        System.out.println("实现的接口:");
        Type[] interfaces = clz.getGenericInterfaces();
        for (Type t : interfaces) {
            System.out.println(t);
            // 如果接口是参数化类型
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) t;
                //得到实际的类型参数
                Type[] typeArgs = pt.getActualTypeArguments();
                for (Type ta : typeArgs) {
                    System.out.println("--实际的类型参数:" + ta);
                }
            }
        }
        System.out.println("-------------------------------------");

        System.out.println("[CallbackTest类中泛型方法的泛型信息]");
        Class clazz = CallbackTest.class;
        Method method = clazz.getMethods()[0];
        System.out.println("方法参数的类型:");
        Type[] paramTypes = method.getGenericParameterTypes();
        for (Type t : paramTypes) {
            System.out.println(t);
            // 如果形参是参数化类型
            if (t instanceof ParameterizedType) {
                ParameterizedType pt = (ParameterizedType) t;
                // 得到实际的类型参数
                Type[] typeArgs = pt.getActualTypeArguments();
                for (Type ta : typeArgs) {
                    System.out.println("--实际的类型参数:" + ta);
                    // 如果是通配符类型
                    if (ta instanceof WildcardType){
                        WildcardType wt = (WildcardType)ta;
                        // 输出类型变量的下限
                        System.out.println("---- "+ Arrays.toString(wt.getLowerBounds()));
                        // 输出类型变量的上限
                        System.out.println("---- "+ Arrays.toString(wt.getUpperBounds()));
                    }
                }
            }
        }

        System.out.println("方法的返回类型:");
        Type returnType = method.getGenericReturnType();
        System.out.println(returnType);
    }
}

技术图片

五、检测类型

package ch15;

interface AA {
}

class X {
    class B {
    }

    public static AA getAA() {
        class C implements AA {
        }
        return new C();
    }
}

enum D {}

public class DetectType {
    public static void main(String[] args) {
        Integer in = 2;
        Class c1 = int.class;

        System.out.printf("c1是否是基本数据类型:%b%n", c1.isPrimitive());

        Class c2 = in.getClass();
        System.out.printf("c2是否是基本数据类型:%b%n", c2.isPrimitive());

        int[] arr = new int[3];
        Class c3 = arr.getClass();
        System.out.printf("c3是否是数组类型:%b%n", c3.isArray());

        Class c4 = D.class;
        System.out.printf("c4是否是枚举类型:%b%n", c4.isEnum());

        Class c5 = AA.class;
        System.out.printf("c5是否是枚举类型:%b%n", c5.isInterface());

        Class c6 = X.B.class;
        System.out.printf("c6是否是内部类:%b%n", c6.isMemberClass());

        Class c7 = X.getAA().getClass();
        System.out.printf("c7是否是局部内部类:%b%n", c7.isLocalClass());

        AA a = new AA() {
        };
        Class c8 = a.getClass();
        System.out.printf("c8是否是匿名类:%b%n", c8.isAnonymousClass());
    }
}

技术图片

Java Class对象

标签:alc   oid   http   exce   private   image   eric   图片   ons   

原文地址:https://www.cnblogs.com/xl4ng/p/14493988.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!