Java类操作

示例

1
2
3
4
5
public interface UserService {
}

public class UserServiceImpl implements UserService {
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@SpringBootTest
class DemoApplicationTests {

@Test
void contextLoads() {
UserServiceImpl userServiceImpl = new UserServiceImpl();

// 父类 isAssignableFrom 子类
System.out.println(UserService.class.isAssignableFrom(UserServiceImpl.class)); // true

// userServiceImpl是否是UserService实例
System.out.println(userServiceImpl instanceof UserService); // true

// UserService能否强转为
System.out.println(UserService.class.isInstance(userServiceImpl)); // true
}

}

spring中常用方法

  • org.springframework.core.annotation.AnnotationUtils
  • org.springframework.util.ClassUtils
  • org.springframework.util.ReflectionUtils