Sunday, 12 April 2020

Spring: Get all subclasses of given class

Spring provides 'ClassPathScanningCandidateComponentProvider' class, it can be used to get all the subclasses of given class.

Maven Dependency used.
<dependency>
 <groupId>org.springframework</groupId>
 <artifactId>spring-context</artifactId>
 <version>5.2.3.RELEASE</version>
</dependency>

Following snippet return all the sub classes of given class.
public static List<Class<?>> getAllSubClasses(Class<?> clazz, String basePackageToScan)
  throws ClassNotFoundException {
 ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
 provider.addIncludeFilter(new AssignableTypeFilter(clazz));

 List<Class<?>> classes = new ArrayList<>();

 Set<BeanDefinition> components = provider.findCandidateComponents(basePackageToScan);
 for (BeanDefinition component : components) {
  Class<?> cls = Class.forName(component.getBeanClassName());

  classes.add(cls);
 }

 return classes;
}

A.java
package com.sample.app.model;

public class A {

}

B.java
package com.sample.app.model;

public class B extends A{

}

C.java
package com.sample.app.model;

public class C extends B{

}

D.java
package com.sample.app.model;

public class D extends A{

}

App.java
package com.sample.app;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.type.filter.AssignableTypeFilter;

import com.sample.app.model.A;

public class App {

 public static List<Class<?>> getAllSubClasses(Class<?> clazz, String basePackageToScan)
   throws ClassNotFoundException {
  ClassPathScanningCandidateComponentProvider provider = new ClassPathScanningCandidateComponentProvider(false);
  provider.addIncludeFilter(new AssignableTypeFilter(clazz));

  List<Class<?>> classes = new ArrayList<>();

  Set<BeanDefinition> components = provider.findCandidateComponents(basePackageToScan);
  for (BeanDefinition component : components) {
   Class<?> cls = Class.forName(component.getBeanClassName());

   classes.add(cls);
  }

  return classes;
 }

 public static void main(String args[]) throws ClassNotFoundException {

  Class<?> clazz = A.class;
  String basePackageToScan = "com/sample/app";

  System.out.println("Sub classes of " + clazz.getName() + " are :");
  List<Class<?>> subClasses = getAllSubClasses(clazz, basePackageToScan);

  for (Class<?> subClazz : subClasses) {
   System.out.println(subClazz.getName());
  }

 }
}

Output

Sub classes of com.sample.app.model.A are :
com.sample.app.model.A
com.sample.app.model.B
com.sample.app.model.C
com.sample.app.model.D


Previous                                                    Next                                                    Home

No comments:

Post a Comment