自定义 Java 对类路径资源加载的 URL 支持
在 Java 中,开发人员可以利用各种 URL 协议访问多功能资源加载 API。然而,虽然“file://”和“http://”等协议有助于从特定位置检索资源,但可能需要从应用程序的类路径访问资源,而无需显式指定 jar 或类文件夹。本文探讨了满足此要求的解决方案,引入了用于基于类路径的资源加载的自定义 URL 协议和流处理程序。
实现自定义流处理程序
解决方案的核心是一个打开的 URLStreamHandler到指定 URL 的连接。此处理程序必须使用“简单”包名称作为支持的协议向 URL 类注册。
package org.my.protocols.classpath; import java.net.URL; import java.net.URLConnection; import java.net.URLStreamHandler; public class Handler extends URLStreamHandler { private final ClassLoader classLoader; public Handler() { this.classLoader = getClass().getClassLoader(); } @Override protected URLConnection openConnection(URL u) /*throws IOException*/ { final URL resourceUrl = classLoader.getResource(u.getPath()); return resourceUrl.openConnection(); } }
使用自定义协议
要使用自定义协议加载资源,请使用以下语法:
new URL("classpath:org/my/package/resource.extension").openConnection();
通过指定相对于类路径的路径,可以在不指定资源在类路径中的具体位置的情况下加载资源
增强处理
为了确保正确处理从类路径加载的资源,可能有必要克服启动配置和 JVM 级处理程序注册的问题。
手动处理程序规范
作为自动处理程序注册的替代方案,可以在 URL 期间手动指定处理程序创建:
new URL( null, "classpath:some/package/resource.extension", new org.my.protocols.classpath.Handler(ClassLoader.getSystemClassLoader()) );
JVM 级处理程序注册
对于应用程序范围的类路径资源加载,建议向 JVM 注册 URLStreamHandlerFactory。这允许自定义处理程序用于所有 URL:
package my.org.url; import java.net.URLStreamHandler; import java.net.URLStreamHandlerFactory; import java.util.HashMap; import java.util.Map; class ConfigurableStreamHandlerFactory implements URLStreamHandlerFactory { private final Map<string urlstreamhandler> protocolHandlers; public ConfigurableStreamHandlerFactory(String protocol, URLStreamHandler urlHandler) { protocolHandlers = new HashMap(); addHandler(protocol, urlHandler); } public void addHandler(String protocol, URLStreamHandler urlHandler) { protocolHandlers.put(protocol, urlHandler); } public URLStreamHandler createURLStreamHandler(String protocol) { return protocolHandlers.get(protocol); } }</string>
要注册工厂,请调用 URL.setURLStreamHandlerFactory() 传递配置的工厂。
结论
通过创建自定义 URLStreamHandler 和流处理程序工厂,可以扩展 Java 的资源加载功能以包含位于应用程序类路径上的资源。这提供了更大的灵活性并简化了从各种来源加载资源的过程。
以上是如何自定义 Java 的 URL 支持以直接从类路径加载资源?的详细内容。更多信息请关注PHP中文网其他相关文章!

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

Atom编辑器mac版下载
最流行的的开源编辑器

记事本++7.3.1
好用且免费的代码编辑器

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具