java--基础--7.12--常用类--Class

本文详细介绍了Java中Class类的几个关键方法,包括isAssignableFrom检查类的继承关系,asSubclass转换类类型,以及cast方法安全类型转换。通过示例代码展示了这些方法的用法和注意事项。
摘要由CSDN通过智能技术生成

java–基础–7.12–常用类–Class


测试代码

package com.example.feizhou.ex;


import ch.qos.logback.core.net.SyslogOutputStream;
import com.example.feizhou.model.User;
import com.example.feizhou.model.UserSon;
import jdk.nashorn.internal.runtime.arrays.IteratorAction;
import org.springframework.stereotype.Component;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import sun.util.resources.cldr.en.TimeZoneNames_en_AU;

import java.io.*;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedType;
import java.lang.reflect.Constructor;
import java.lang.reflect.TypeVariable;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.ProtectionDomain;

public class ClassTest {

    @Test
//    Class <? extends U> asSubclass(Class<U> clazz)
//    Class<? extends T2> aClass = T1.class.asSubclass(T2.class);
    //如果T1是T2的子类或者T1与T2是同一个类,返回T1,否则抛异常ClassCastException
    public void testAsSubclass() {
        Class<? extends User> t1 = UserSon.class.asSubclass(User.class);
        System.out.println("t1:" + t1);
        Class<? extends UserSon> t2 = User.class.asSubclass(UserSon.class);
        System.out.println("t2:" + t2);
    }


    @Test
//    boolean isAssignableFrom(类<?> cls)
//boolean assignableFrom1 = T1.class.isAssignableFrom(T2.class);
//      T1.class表示的类或接口是否与是T2.class表示的类或接口相同
//      或者
//      T1.class表示的类或接口是否是T2.class表示的类的超类或类接口
    public void testIsAssignableFrom() {
        boolean isture1 = User.class.isAssignableFrom(UserSon.class);
        boolean isture2 = UserSon.class.isAssignableFrom(User.class);
        boolean isture3 = User.class.isAssignableFrom(Integer.class);
        System.out.println("isture1:" + isture1);
        System.out.println("isture2:" + isture2);
        System.out.println("isture3:" + isture3);

    }

    @Test
    public void Cast() {
        User cast1 = User.class.cast(new UserSon(1, "111"));
        System.out.println("cast1:" + cast1);
        UserSon cast2 = UserSon.class.cast(new User());
        System.out.println("cast2:" + cast2);
    }

    @Test
    public void forName() throws ClassNotFoundException {
        Class<?> aClass = Class.forName("com.example.feizhou.model.User");
        System.out.println("aClass:" + aClass);
    }

    @Test
    public void getAnnotatedSuperclass() {
        AnnotatedType t1 = UserSon.class.getAnnotatedSuperclass();
        System.out.println("t1:" + t1);
    }

    @Test
    public void getAnnotatedInterfaces() {
        AnnotatedType[] AnnotatedTypes = UserSon.class.getAnnotatedInterfaces();
        System.out.println("接口个数:" + AnnotatedTypes.length);
    }

    @Test
    public void getAnnotation() {
        Annotation annotation = User.class.getAnnotation(Component.class);
        System.out.println("Component:" + annotation.annotationType());
    }

    @Test
    public void getAnnotations() {
        Annotation[] annotations = User.class.getAnnotations();
        for (Annotation annotation : annotations) {
            System.out.println("注解:" + annotation.annotationType());
        }

    }

    @Test
    public void getAnnotationsByType() {
        Annotation[] annotations = User.class.getAnnotationsByType(Component.class);
        for (Annotation annotation : annotations) {
            System.out.println("注解:" + annotation.annotationType());
        }
    }

    @Test
    public void getClasses() {
        Class<?>[] classes = UserSon.class.getClasses();
        for (Class c : classes) {
            System.out.println("类:" + c);
        }
    }

    @Test
    public void getClassLoader() {
        ClassLoader classLoader = UserSon.class.getClassLoader();
        System.out.println("类加载器:" + classLoader);
    }

    @Test
    public void getComponentType() {
        String[] arr = new String[10];
        Class<?> componentType = arr.getClass().getComponentType();
        System.out.println("数组的类型:" + componentType);
    }

    @Test
    public void getConstructor() throws NoSuchMethodException {
        Constructor<User> constructor = User.class.getConstructor();
        System.out.println("类构造:" + constructor);
    }

    @Test
    public void getDeclaredAnnotation() {
        Component component = User.class.getDeclaredAnnotation(Component.class);
        System.out.println("component:" + component);
    }

    @Test
    public void getProtectionDomain() {
        ProtectionDomain protectionDomain = User.class.getProtectionDomain();
        System.out.println("protectionDomain:" + protectionDomain);
    }

    @Test
    public void getResource() {
        URL resource = User.class.getResource("/");
        System.out.println("resource:" + resource);
    }

    @Test
    public void getResourceAsStream() throws IOException {
        InputStream in = User.class.getResourceAsStream("IUserSon.class");

        BufferedInputStream bis = new BufferedInputStream(in);

        byte[] bys = new byte[1024];
        int len = 0;
        while ((len = bis.read(bys)) != -1) {
             System.out.println(new String(bys));
        }
        bis.close();
    }
    @Test
    public void getSimpleName() {
        String simpleName = User.class.getSimpleName();
        System.out.println("simpleName:" + simpleName);

    }
    @Test
    public void getTypeName() {
        String typeName = User.class.getTypeName();
        System.out.println("typeName:" + typeName);
    }
    @Test
    public void getTypeParameters() {
        TypeVariable<Class<User>>[] typeParameters = User.class.getTypeParameters();
    }
    @Test
    public void isAnnotation() {
        boolean annotation = Component.class.isAnnotation();
        System.out.println("annotation:" + annotation);
    }
    @Test
    public void isAnnotationPresent() {
        boolean isAnnotationPresent = User.class.isAnnotationPresent(Component.class);
        System.out.println("isAnnotationPresent:" + isAnnotationPresent);
    }
    @Test
     public void isAnonymousClass() {
        boolean anonymousClass = User.class.isAnonymousClass();
        System.out.println("anonymousClass:" + anonymousClass);
    }
    @Test
    public void isArray() {
        boolean isArray = new byte[1024].getClass().isArray();
        System.out.println("isArray:" + isArray);
    }
    @Test
    public void isInstance() {
        boolean instance = User.class.isInstance(new UserSon(12, "111"));
        System.out.println("instance:" + instance);
    }
    @Test
    public void isLocalClass() {
        class LocalInnerClass { }
        boolean localClass1 = LocalInnerClass.class.isLocalClass();
        System.out.println("localClass1:" + localClass1);
    }
    @Test
    public void isMemberClass() {
        boolean memberClass = new UserSon().new A().getClass().isMemberClass();
        System.out.println("memberClass:" + memberClass);
    }

    @Test
    public void isPrimitive() {
        boolean primitive = Integer.class.isPrimitive();
        boolean primitive2 = int.class.isPrimitive();
        System.out.println("primitive:" + primitive);
        System.out.println("primitive2:" + primitive2);
    }

    @Test
    public void toGenericString() {
        String s = User.class.toGenericString();
        System.out.println("s:" + s);
    }

}


----------------------------
 

@Component
public interface IUserSon  {
    String getUserSon();
}


----------------------------
@Component
public class User extends  UserFather {

    private  int id;
    private  String name;


    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public User() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public static void show() {
        System.out.println("User function");
    }
}



----------------------------
 
public class UserFather {

    private  int id;
    private  String name;


    public UserFather(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public UserFather() {
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }

    public static void show() {
        System.out.println("User function");
    }
}


----------------------------
 
public class UserSon  extends  User implements  IUserSon{
    public UserSon(int id, String name) {
        super(id, name);
    }
    public UserSon() {
    }

    public static void show() {
        System.out.println("UserSon function");
    }

    @Override
    public String getUserSon() {
        return "this is getUserSon" ;
    }



    public  class A{
    }
    public  class B{
    }
} 

1、public boolean isAssignableFrom(Class<?> cls)

boolean assignableFrom1 = T1.class.isAssignableFrom(T2.class);
T1.class表示的类或接口是否与是T2.class表示的类或接口相同
或者
T1.class表示的类或接口是否是T2.class表示的类的超类或类接口

public void testIsAssignableFrom() {
    boolean isture1 = User.class.isAssignableFrom(UserSon.class);
    boolean isture2 = UserSon.class.isAssignableFrom(User.class);
    boolean isture3 = User.class.isAssignableFrom(Integer.class);
   System.out.println("isture1:"+isture1);
   System.out.println("isture2:"+isture2);
   System.out.println("isture3:"+isture3);
   输出:
   isture1:true
   isture2:false
   isture3:false
}

2、public <U> Class<? extends U> asSubclass(Class<U> clazz)

Class<? extends T2> aClass = T1.class.asSubclass(T2.class);

如果T1是T2的子类,返回T1,否则抛异常ClassCastException


public <U> Class<? extends U> asSubclass(Class<U> clazz) {

    if (clazz.isAssignableFrom(this))
        return (Class<? extends U>) this;
    else
        throw new ClassCastException(this.toString());
} 



public void testAsSubclass() {
    Class<? extends User> t1 = UserSon.class.asSubclass(User.class);
     System.out.println("t1:"+t1);
    Class<? extends UserSon> t2 = User.class.asSubclass(UserSon.class);
    System.out.println("t2:"+t2);
}

3、public T cast(Object obj)


T cast = T.class.cast(Object obj);
将obj强转为T。
此方法只能转换当前类型或其子类下的对象,只是简单进行强转。



public T cast(Object obj) {
    if (obj != null && !isInstance(obj))
        throw new ClassCastException(cannotCastMsg(obj));
    return (T) obj;
}


@Test
public void  Cast() {
    User cast1 = User.class.cast(new UserSon(1,"111"));
    System.out.println("cast1:"+cast1);

    UserSon cast2 = UserSon.class.cast(new User());
    System.out.println("cast2:"+cast2);
}

4、public Class<?>[] getClasses()

Class<?>[] classes = T1.class.getClasses();
返回:得到T1类及其父类所有的public的内部类


 

@Test
public void  getClasses() {
    Class<?>[] classes = UserSon.class.getClasses();
    for (Class c : classes) {
        System.out.println("类:"+c);
    }
}

输出:

类:class com.example.feizhou.model.UserSon$B
类:class com.example.feizhou.model.UserSon$A

5、public static Class<?> forName(String className) throws ClassNotFoundException

Class<?> aClass = Class.forName("className");

返回className的类对象



@Test
public void  forName() throws ClassNotFoundException {
    Class<?> aClass = Class.forName("com.example.feizhou.model.User");
    System.out.println("aClass:"+aClass);
    输出:aClass:class com.example.feizhou.model.User
}

6、public AnnotatedType getAnnotatedSuperclass()

AnnotatedType t1 = T1.class.getAnnotatedSuperclass();
如果T1是Object类,接口类型,数组类型,基元类型或void,则返回值为null 。
否则返回T1父类的注解类型AnnotatedType



源码
public AnnotatedType getAnnotatedSuperclass() {
    if (this == Object.class ||
            isInterface() ||
            isArray() ||
            isPrimitive() ||
            this == Void.TYPE) {
        return null;
    }
return TypeAnnotationParser.buildAnnotatedSuperclass(getRawTypeAnnotations(), getConstantPool(), this);
}




@Test
public void  getAnnotatedSuperclass() {
    AnnotatedType t1 = UserSon.class.getAnnotatedSuperclass();
    System.out.println("t1:"+t1);
    
}

输出:
t1:sun.reflect.annotation.AnnotatedTypeFactory$AnnotatedTypeBaseImpl@4566e5bd

7、public AnnotatedType[] getAnnotatedInterfaces()

AnnotatedType[] AnnotatedTypes = T1.class.getAnnotatedInterfaces();
返回T1的接口注解类型AnnotatedType[]



@Test
public void  getAnnotatedInterfaces() {
    AnnotatedType[] AnnotatedTypes = UserSon.class.getAnnotatedInterfaces();
        System.out.println("接口个数:"+AnnotatedTypes.length);
}


输出:

接口个数:1

8、public <A extends Annotation> A getAnnotation(Class<A> annotationClass)

Annotation annotation = T1.class.getAnnotation(Component.class);
返回当前T1类Component注解,如果没有,返回null


@Test
public void  getAnnotation() {
    Annotation annotation = User.class.getAnnotation(Component.class);
    System.out.println("Component:"+annotation.annotationType());
}

输出:

Component:interface org.springframework.stereotype.Component

9、public Annotation[] getAnnotations()

Annotation[] annotations = T1.class.getAnnotations();
返回T1类的所有注解。


@Test
public void  getAnnotations() {
    Annotation[] annotations = User.class.getAnnotations();
    for (Annotation annotation : annotations) {
        System.out.println("注解:"+annotation.annotationType());
    }
}

输出:

注解:interface org.springframework.stereotype.Component

10、public <A extends Annotation> A[] getAnnotationsByType(Class<A> annotationClass)

Annotation[] annotations = T1.class.getAnnotationsByType(Component.class);

返回T1类所有Component类型的注解


@Test
public void  getAnnotationsByType() {
    Annotation[] annotations = User.class.getAnnotationsByType(Component.class);
    for (Annotation annotation : annotations) {
        System.out.println("注解:"+annotation.annotationType());
    }
}

输出: 
注解:interface org.springframework.stereotype.Component

11、public ClassLoader getClassLoader()

ClassLoader classLoader = T1.class.getClassLoader();
返回T1类的加载器

测试


@Test
public void  getClassLoader() {
    ClassLoader classLoader = UserSon.class.getClassLoader();
    System.out.println("类加载器:"+classLoader);
}

输出: 
类加载器:sun.misc.Launcher$AppClassLoader@18b4aac2

12、public Class<?> getComponentType()


Class<?> componentType = T1.getClass().getComponentType();
返回T1数组的类型Class。 如果 T1不是数组,返回null。

测试

@Test
public void  getComponentType() {
    String [] arr = new String[10];
    Class<?> componentType = arr.getClass().getComponentType();
    System.out.println("数组的类型:"+componentType);
}
输出: 
数组的类型:class java.lang.String

13、public Constructor<T> getConstructor(Class<?>... parameterTypes)

Constructor<User> constructor = T1.class.getConstructor();
返回T1类的无参构造

测试


@Test
public void  getConstructor() throws NoSuchMethodException {
    Constructor<User> constructor = User.class.getConstructor();
    System.out.println("类构造:"+constructor);
}

输出:

类构造:public com.example.feizhou.model.User()

14、public Constructor<?>[] getConstructors()

返回类的所有公共构造对象。

15、public <A extends Annotation> A getDeclaredAnnotation(Class<A> annotationClass)


返回指定类型的元素注解,指定类型不存在返回null。 此方法忽略继承的注解。
 
 
@Test
public void  getDeclaredAnnotation()  {
    Component component = User.class.getDeclaredAnnotation(Component.class);
    System.out.println("component:"+component);
}


输出: 
component:@org.springframework.stereotype.Component(value=)

16、public <A extends Annotation> A[] getDeclaredAnnotationsByType(Class<A> annotationClass)

返回该类指定类型的注解数组该类的注解类型直接存在或间接存在,此方法忽略继承的注解

17、public Class<?>[] getDeclaredClasses()

返回类中定义的公共、私有、保护的内部类

18、public Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)

返回规定参数类型的所有构造器,包括public的和非public的,当然也包括private的。

19、public Constructor<?>[]  getConstructors()

返回此 Class 对象的所有构造方法。不仅是公共的。

20 public Field getDeclaredField(String name)

返回一个指定字段名的Field 对象

21、public Field[] getDeclaredFields()

返回类或接口所声明的所有字段。

22、public Method getDeclaredMethod(String name,  Class<?>... parameterTypes)

返回Class所表示的类或接口指定的方法。

23、public Method[] getMethods()

 返回class表示的类或接口的所有公共方法,包括那些从父类和超接口继承的方法。

24、public int getModifiers()


返回此类或接口以整数编码的 Java 语言修饰符。

25、public String getName()

 返回Class 对象所表示的实体名称类、接口、数组类、基本类型或void。

26、public Package getPackage()

返回获取此类的包

27、public URL getResource(String name)

返回定名称的资源。

测试


@Test
public void  getResource()  {
    URL resource = User.class.getResource("/");
    System.out.println("resource:"+resource);

}

输出:
resource:file:/F:/Java/workspace/idea_learn/ex/target/test-classes/

28、public InputStream getResourceAsStream(String name)

  返回定名称的资源。

测试


@Test
public void getResourceAsStream() throws IOException {
    InputStream in = User.class.getResourceAsStream("IUserSon.class");

    BufferedInputStream bis = new BufferedInputStream(in);

    byte[] bys = new byte[1024];
    int len = 0;
    while ((len = bis.read(bys)) != -1) {
         System.out.println(new String(bys));
    }
    bis.close();
}



29、public String getSimpleName()

返回源代码中给出的基础类的简单名称。

@Test
public void getSimpleName() {
    String simpleName = User.class.getSimpleName();
    System.out.println("simpleName:" + simpleName);
}

输出: 
simpleName:User

30、public Class<? super T> getSuperclass()


返回Class的实体父类的Class。实体:类、接口、基本类型或 void

31、public String getTypeName()

返回该class的全类名名称

@Test
public void getTypeName() {
    String typeName = User.class.getTypeName();
    System.out.println("typeName:" + typeName);
}

输出:
typeName:com.example.feizhou.model.User

32、public TypeVariable<Class<T>>[] getTypeParameters()


返回一个代表该泛型声明中声明的类型变量TypeVariable对象的数组。

TypeVariable<Class<User>>[] typeParameters = User.class.getTypeParameters();


33、public boolean isAnnotation()

 
boolean annotation = T1.class.isAnnotation();

如果 T1是一个注解,返回 true

测试


@Test
public void isAnnotation() {
    boolean annotation = Component.class.isAnnotation();
    System.out.println("annotation:" + annotation);
}

输出:

annotation:true

34、public boolean isAnnotationPresent(类<? extends Annotation> annotationClass)


boolean isAnnotationPresent = T1.class.isAnnotationPresent(Component.class);

如果T1有Component注解,则返回 true,否则返回 false。

如果指定类型的注释存在于此类上,则返回 true,否则返回 false。


测试


@Test
public void isAnnotationPresent() {
    boolean isAnnotationPresent = User.class.isAnnotationPresent(Component.class);
    System.out.println("isAnnotationPresent:" + isAnnotationPresent);
}

输出:

isAnnotationPresent:true

35、public boolean isAnonymousClass()

当且仅当底层类是匿名类(比如:匿名内部类)时返回 true

测试


public void isAnonymousClass() {
    boolean anonymousClass = User.class.isAnonymousClass();
    System.out.println("anonymousClass:" + anonymousClass);
}

输出: 
anonymousClass:false

36、public boolean isArray()


判定此 Class 对象是不是数组类。

测试


@Test
public void isArray() {
    boolean isArray = new byte[1024].getClass().isArray();
    System.out.println("isArray:" + isArray);
}


输出:

isArray:true

37、public boolean isEnum()

判定此 Class 对象是不是枚举类。

38、public boolean isInstance(Object obj)

boolean instance = T1.class.isInstance(T2);
判断T2能不能被转化T1
它与Java语言instanceof运算符等效。


测试

@Test
public void isInstance() {
    boolean instance = User.class.isInstance(new UserSon(12, "111"));
    System.out.println("instance:" + instance);
}
输出: 
instance:true 

39、public boolean isInterface()


判定此 Class 对象是不是接口类型。

40、public boolean isLocalClass()

boolean localClass1 = T1.class.isLocalClass();
查看T1是不是局部内部类。

测试


@Test
public void isLocalClass() {
    class LocalInnerClass { }
    boolean localClass1 = LocalInnerClass.class.isLocalClass();
    System.out.println("localClass1:" + localClass1);
}
输出:

localClass1:true

41、public boolean isMemberClass()


查看是否成员内部类。

测试


@Test
public void isMemberClass() {
    boolean memberClass = new UserSon().new A().getClass().isMemberClass();
    System.out.println("memberClass:" + memberClass);
}
输出:

memberClass:true


42、public boolean isPrimitive()

查看是否基本数据类型

测试


@Test
public void isPrimitive() {
    boolean primitive = Integer.class.isPrimitive();
    boolean primitive2 = int.class.isPrimitive();
    System.out.println("primitive:" + primitive);
    System.out.println("primitive2:" + primitive2);
}


输出:

primitive:false
primitive2:true

43、public boolean isSynthetic()

测试该类是否由编译器编译成class文件时所增加的,否则它是由编程人员编写java源文件时所编写的。

44、public T newInstance()

使用该类的无参构造器创建实例

45、public String toGenericString()

返回该对象的描述,包含标识符等。

测试


@Test
public void toGenericString() {
    String s = User.class.toGenericString();
    System.out.println("s:" + s);
}
输出:
s:public class com.example.feizhou.model.User


​​​​​

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值