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

===

===

相关推荐
爱吃喵的鲤鱼8 分钟前
linux进程的状态之环境变量
linux·运维·服务器·开发语言·c++
LuckyLay14 分钟前
Spring学习笔记_27——@EnableLoadTimeWeaving
java·spring boot·spring
向阳121827 分钟前
Dubbo负载均衡
java·运维·负载均衡·dubbo
DARLING Zero two♡34 分钟前
关于我、重生到500年前凭借C语言改变世界科技vlog.16——万字详解指针概念及技巧
c语言·开发语言·科技
Gu Gu Study37 分钟前
【用Java学习数据结构系列】泛型上界与通配符上界
java·开发语言
芊寻(嵌入式)1 小时前
C转C++学习笔记--基础知识摘录总结
开发语言·c++·笔记·学习
WaaTong1 小时前
《重学Java设计模式》之 原型模式
java·设计模式·原型模式
m0_743048441 小时前
初识Java EE和Spring Boot
java·java-ee
AskHarries1 小时前
Java字节码增强库ByteBuddy
java·后端
一颗松鼠1 小时前
JavaScript 闭包是什么?简单到看完就理解!
开发语言·前端·javascript·ecmascript