001/******************************************************************************* 002 * This software is provided as a supplement to the authors' textbooks on digital 003 * image processing published by Springer-Verlag in various languages and editions. 004 * Permission to use and distribute this software is granted under the BSD 2-Clause 005 * "Simplified" License (see http://opensource.org/licenses/BSD-2-Clause). 006 * Copyright (c) 2006-2023 Wilhelm Burger, Mark J. Burge. All rights reserved. 007 * Visit https://imagingbook.com for additional details. 008 ******************************************************************************/ 009package imagingbook.core; 010 011import java.net.URI; 012import java.net.URISyntaxException; 013import java.nio.file.Path; 014import java.nio.file.Paths; 015 016public abstract class ClassUtils { 017 018 019 public static String getModuleFromPackage(Class<?> clazz) { 020 Package pkg = clazz.getPackage(); 021 if (pkg == null) 022 return null; 023 String specs = pkg.getSpecificationTitle(); 024 if (specs == null) 025 return null; 026 int k = specs.lastIndexOf(':'); 027 if (k < 0) { 028 return null; 029 } 030 return specs.substring(specs.lastIndexOf(':') + 1); 031 } 032 033 /** 034 * Tries to discover the name of the module defining the specified class. 035 * Call with arguments (clazz, "imagingbook-public"). 036 * 037 * @param clazz a class instance 038 * @param projectName the name of the containing project 039 * @return the module name or {@code null} if not found. 040 */ 041 public static String getModuleFromClasspath(Class<?> clazz, String projectName) { 042 Path ppp = Paths.get(projectName); 043 String moduleName = null; 044 try { 045 URI uri = clazz.getProtectionDomain().getCodeSource().getLocation().toURI(); 046 if (uri != null) { 047 Path p = Paths.get(uri); 048 int n = p.getNameCount(); 049 int k = -1; 050 // find 'projectName' in path components: 051 for (int i = 0; i < n; i++) { 052 if (p.getName(i).equals(ppp)) { 053 k = i + 1; 054 break; 055 } 056 } 057 // the following component should be the module part 058 if (k >= 0 && k < n-1) { 059 moduleName = p.getName(k).toString(); 060 } 061 } 062 } catch (URISyntaxException e) { } 063 return moduleName; 064 } 065 066 067 // ----------------------------------------------------------------- 068 069 public static void main(String[] args) throws URISyntaxException { 070 071 Class<?> clazz = FileUtils.class; 072 String specs = clazz.getPackage().getSpecificationTitle(); 073 System.out.println("specs = " + specs); 074 075 System.out.println("module from class = " + clazz.getModule().getName()); 076 System.out.println("module from package = " + getModuleFromPackage(clazz)); 077 System.out.println("module from classpath = " + getModuleFromClasspath(clazz, "imagingbook-public")); 078 079 } 080}