【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包内容

===

===

相关推荐
Amarantine、沐风倩✨21 分钟前
设计一个监控摄像头物联网IOT(webRTC、音视频、文件存储)
java·物联网·音视频·webrtc·html5·视频编解码·七牛云存储
Kisorge1 小时前
【C语言】指针数组、数组指针、函数指针、指针函数、函数指针数组、回调函数
c语言·开发语言
路在脚下@1 小时前
spring boot的配置文件属性注入到类的静态属性
java·spring boot·sql
森屿Serien1 小时前
Spring Boot常用注解
java·spring boot·后端
gywl2 小时前
openEuler VM虚拟机操作(期末考试)
linux·服务器·网络·windows·http·centos
轻口味2 小时前
命名空间与模块化概述
开发语言·前端·javascript
苹果醋32 小时前
React源码02 - 基础知识 React API 一览
java·运维·spring boot·mysql·nginx
某柚啊3 小时前
Windows开启IIS后依然出现http error 503.the service is unavailable
windows·http
晓纪同学3 小时前
QT-简单视觉框架代码
开发语言·qt
威桑3 小时前
Qt SizePolicy详解:minimum 与 minimumExpanding 的区别
开发语言·qt·扩张策略