【java】指定类,指定package,找到package下面,这个类的所有子类

目录

■java代码

■注意

■运行效果(Eclipse中运行)

■包的结构

■生成jar包时,出现问题解决

■jar包运行时,上面代码是否有效---无效!

===jar运行效果

■jar包内容


=============

■java代码

复制代码
package com.sxz.study.reflect;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

public class Test {
	public static void main(String[] args) {
		
		System.out.println("Test Reflect");

		// Search Target Class
		Class<?> searchClass = com.sxz.study.classload.Parent.class;

		// Search Target Package Name
		String searchPackageName = "com.sxz.study";

		List<Class<?>> subClasses = getSubClasses(searchClass, searchPackageName);
		System.out.println(" Result ========================================== Result");
		for (Class<?> subClass : subClasses) {
			System.out.println(subClass.getName());
		}
	}

	/**
	 * 
	 * Get SubClass Search From Package
	 * 
	 * @param parentClass
	 * @param packageName
	 * @return
	 */
	public static List<Class<?>> getSubClasses(Class<?> parentClass, String packageName) {
		List<Class<?>> subClasses = new ArrayList<>();
		try {

			System.out.println("========================================== Now Load Package Begin.");
			Package[] packages = Package.getPackages();
			for (Package pkg : packages) {
				System.out.println(pkg.getName());
			}
			System.out.println("========================================== Now Load Package End.");

			// Get Class from package.
			List<Class<?>> classes = getClasses(packageName);

			for (Class<?> clazz : classes) {

				System.out.println(clazz.getTypeName());
				// Is SubClass ?
				if (parentClass.isAssignableFrom(clazz) && !clazz.equals(parentClass)) {
					subClasses.add(clazz);
				}
			}
		} catch (ClassNotFoundException ex) {
			ex.printStackTrace();
		}

		return subClasses;

	}

	/**
	 * 
	 * Get Class from package.
	 * 
	 * @param packageName
	 * @return
	 * @throws ClassNotFoundException
	 */
	public static List<Class<?>> getClasses(String packageName) throws ClassNotFoundException {
		ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
		String path = packageName.replace('.', '/');
		Enumeration<URL> resources;
		try {
			resources = classLoader.getResources(path);
		} catch (IOException e) {
			throw new ClassNotFoundException("Package not found", e);
		}
		List<File> dirs = new ArrayList<>();
		while (resources.hasMoreElements()) {
			URL resource = resources.nextElement();
			dirs.add(new File(resource.getFile()));
		}
		List<Class<?>> classes = new ArrayList<>();
		for (File directory : dirs) {
			classes.addAll(findClasses(directory, packageName));
		}
		return classes;
	}

	/**
	 * 
	 * @param directory
	 * @param packageName
	 * @return
	 * @throws ClassNotFoundException
	 */
	private static List<Class<?>> findClasses(File directory, String packageName) throws ClassNotFoundException {
		List<Class<?>> classes = new ArrayList<>();
		if (!directory.exists()) {
			return classes;
		}
		File[] files = directory.listFiles();
		for (File file : files) {
			if (file.isDirectory()) {
				assert !file.getName().contains(".");
				// 使用到了递归
				classes.addAll(findClasses(file, packageName + "." + file.getName()));
			} else if (file.getName().endsWith(".class")) {
				classes.add(
						Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
			}
		}
		return classes;
	}

}

===

■注意

所有被扫描的类,都会被加载

■运行效果(Eclipse中运行)

Test Reflect

========================================== Now Load Package Begin.

sun.reflect

java.util

sun.reflect.annotation

java.lang.annotation

java.nio

sun.nio

java.security.cert

java.util.zip

sun.launcher

sun.security.action

java.nio.file

com.sxz.study.reflect

java.nio.charset

sun.net.www

java.lang.ref

java.net

jdk.internal.util

sun.net.www.protocol.file

java.lang.invoke

sun.util.locale

sun.reflect.generics.repository

com.sxz.study.classload

sun.misc

java.lang.reflect

sun.net.util

java.security

sun.net.www.protocol.jar

java.util.concurrent

sun.io

java.util.concurrent.atomic

java.util.concurrent.locks

sun.util

java.lang

sun.nio.cs.ext

java.io

sun.reflect.misc

sun.nio.ch

java.util.jar

sun.nio.cs

java.util.function

java.nio.charset.spi

sun.security.util

sun.usagetracker

========================================== Now Load Package End.

父类--静态变量

父类--静态初始化块

子类--静态变量

子类--静态初始化块

Face--静态变量

Face--静态初始化块

Face--构造器

Person invoked

com.sxz.study.aes.AESUTil

com.sxz.study.aes.TestAES

com.sxz.study.alogrithm.TestAlogrithom2

com.sxz.study.aop.AspectTest

com.sxz.study.aop.MyAspect

com.sxz.study.classload.Child

com.sxz.study.classload.ClassLoadTest

com.sxz.study.classload.Face

com.sxz.study.classload.Parent

com.sxz.study.classload.Person$1

com.sxz.study.classload.Person

com.sxz.study.conf.AppConf

com.sxz.study.extend.Test

com.sxz.study.file.Test

com.sxz.study.file.Test2

com.sxz.study.http.HttpClientTest

com.sxz.study.json.TestBean

com.sxz.study.json.TestJson

com.sxz.study.jvm.Test$1

com.sxz.study.jvm.Test

com.sxz.study.messageDigest.MessageDigestTest

com.sxz.study.objectReflect.Person

com.sxz.study.objectReflect.Test

com.sxz.study.observer.ConcreteObserver

com.sxz.study.observer.ConcreteSubject

com.sxz.study.observer.Observer

com.sxz.study.observer.ObserverPatternExample

com.sxz.study.observer.Subject

com.sxz.study.process.TestProcess

com.sxz.study.reflect.Test

com.sxz.study.socket.Client

com.sxz.study.socket.Server

com.sxz.study.thread.ThreadStudy1$1

com.sxz.study.thread.ThreadStudy1

com.sxz.study.type.Test

Result ========================================== Result

com.sxz.study.classload.Child

==

■包的结构

==

===

■生成jar包时,出现问题解决

set path=c:\java\bin;c:\maven\bin;%path%

C:\dev\MyJava001

mvn clean package -Dmaven.test.skip=true --settings C:\sxz\Dev\Maven\repository\settings.xml

问题

C:\dev\MyJava001\src\main\java\com\sxz\study\reflect\Test.java使用了未经检查或不安全的操作。

复制代码
[INFO] --- maven-compiler-plugin:3.8.1:compile (default-compile) @ Test001 ---
[INFO] Changes detected - recompiling the module!
[INFO] Compiling 45 source files to C:\dev\MyJava001\target\classes
[INFO] /C:/dev/MyJava001/src/main/java/com/sxz/study/reflect/Test.java: C:\dev\MyJava001\src\main\java\com\sxz\study\reflect\Test.java使用了未经检查或不安全的操作。
[INFO] /C:/dev/MyJava001/src/main/java/com/sxz/study/reflect/Test.java: 有关详细信息, 请使用 -Xlint:unchecked 重新编译。
[INFO]

解决

Class

Class<?>

■jar包运行时,上面代码是否有效---无效!

复制代码
G:\Jar\2024\0615>java -cp ./Test001-0.0.1-SNAPSHOT.jar com.sxz.study.reflect.Test

===jar运行效果

===

■jar包内容

===

===

相关推荐
JavaPub-rodert1 分钟前
一道go面试题
开发语言·后端·golang
6<74 分钟前
【go】静态类型与动态类型
开发语言·后端·golang
柚几哥哥5 分钟前
IntelliJ IDEA全栈Git指南:从零构建到高效协作开发
java·git·intellij-idea
技术liul9 分钟前
解决Spring Boot Configuration Annotation Processor not configured
java·spring boot·后端
chushiyunen21 分钟前
dom操作笔记、xml和document等
xml·java·笔记
whisperrr.21 分钟前
【spring01】Spring 管理 Bean-IOC,基于 XML 配置 bean
xml·java·spring
chushiyunen24 分钟前
tomcat使用笔记、启动失败但是未打印日志
java·笔记·tomcat
天上掉下来个程小白30 分钟前
HttpClient-03.入门案例-发送POST方式请求
java·spring·httpclient·苍穹外卖
ModestCoder_40 分钟前
将一个新的机器人模型导入最新版isaacLab进行训练(以unitree H1_2为例)
android·java·机器人
sukalot1 小时前
Windows 图形显示驱动开发-WDDM 2.4功能-GPU 半虚拟化(十一)
windows·驱动开发