如何获取Class实例

2021-09-26 09:38:37 浏览数 (1)

  1. 类型.class
  2. 类实例.getClass()
  3. Class.forName(类的权限定类名)
代码语言:javascript复制
public class Test {
   public static void main(String[] args) throws ClassNotFoundException {
      Class<Test> testClass = Test.class;
      Test test = new Test();
      Class<? extends Test> testClass1 = test.getClass();
      Class<Test> testClass2 = (Class<Test>) Class.forName("com.ldx.test.Test");
   }
}

2.2 使用Class实例

创建一个User

代码语言:javascript复制
package com.ldx.test;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter
@Setter
@ToString
public class User {
   private String name;

   private Integer age;

   public boolean isAdmin(String name) {
      if("admin".equals(name)) {
         return true;
      }
      return false;
   }
}

创建一个测试类Test

代码语言:javascript复制
package com.ldx.test;

import lombok.extern.slf4j.Slf4j;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Arrays;

@Slf4j
public class Test {
   public static void main(String[] args) throws Exception {
      Class<User> userClass = User.class;
      Field[] declaredFields = userClass.getDeclaredFields();
      log.info("User类的名称:{}", userClass.getSimpleName());
      log.info("User类的权限定类名:{}", userClass.getName());
      log.info("User类的字段有:{}", Arrays.toString(declaredFields));
      log.info("User类的方法有:{}", Arrays.toString(userClass.getDeclaredMethods()));
      Method isAdmin = userClass.getMethod("isAdmin", String.class);
      log.info("User::isAdmin方法返回值为:"   isAdmin.invoke(userClass.newInstance(), "admin"));
   }
}

输出内容如下:

代码语言:javascript复制
com.ldx.test.Test - User类的名称:User
com.ldx.test.Test - User类的权限定类名:com.ldx.test.User
com.ldx.test.Test - User类的字段有:[private java.lang.String com.ldx.test.User.name, private java.lang.Integer com.ldx.test.User.age]
com.ldx.test.Test - User类的方法有:[public boolean com.ldx.test.User.isAdmin(java.lang.String), public java.lang.Integer com.ldx.test.User.getAge(), public void com.ldx.test.User.setAge(java.lang.Integer), public java.lang.String com.ldx.test.User.toString(), public java.lang.String com.ldx.test.User.getName(), public void com.ldx.test.User.setName(java.lang.String)]
com.ldx.test.Test - User::isAdmin方法返回值为:true

0 人点赞