Skip to content

Instantly share code, notes, and snippets.

@bartdag
Created June 30, 2011 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bartdag/1056992 to your computer and use it in GitHub Desktop.
Save bartdag/1056992 to your computer and use it in GitHub Desktop.
Java: Getting FQNs from a simple name
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* Main application/strategy
*/
public class Application {
private List<PackageProvider> providers;
private Set<String> packages;
/**
* The constructor.
*/
public Application() {
providers = new ArrayList<PackageProvider>();
providers.add(new RuntimePackageProvider());
providers.add(new ClasspathPackageProvider());
providers.add(new JavaLibraryPackageProvider());
// Only add this line if the code is executed inside an Eclipse plug-in
providers.add(new EclipsePackageProvider());
// Add your own provider here (e.g., web application provider)
}
private Set<String> getPackages() {
Set<String> packages = new HashSet<String>();
for (PackageProvider provider : providers) {
packages.addAll(provider.getPackages());
}
return packages;
}
public List<String> getFQNs(String simpleName) {
if (this.packages == null) {
this.packages = getPackages();
}
List<String> fqns = new ArrayList<String>();
for (String aPackage : packages) {
try {
String fqn = aPackage + "." + simpleName;
Class.forName(fqn);
fqns.add(fqn);
} catch (Exception e) {
// Ignore
}
}
return fqns;
}
public static void main(String[] args) {
Application app = new Application();
System.out.println(app.getFQNs("File"));
System.out.println(app.getFQNs("List"));
System.out.println(app.getFQNs("IResource"));
}
}
import java.io.File;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Set;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Computes the list of packages provided by all paths (directories and jar files) on the classpath.
*/
public class ClasspathPackageProvider implements PackageProvider {
@Override
public Collection<String> getPackages() {
String classpath = System.getProperty("java.class.path");
return getPackageFromClassPath(classpath);
}
public static Set<String> getPackageFromClassPath(String classpath) {
Set<String> packages = new HashSet<String>();
String[] paths = classpath.split(File.pathSeparator);
for (String path : paths) {
if (path.trim().length() == 0) {
continue;
} else {
File file = new File(path);
if (file.exists()) {
String childPath = file.getAbsolutePath();
if (childPath.endsWith(".jar")) {
packages.addAll(ClasspathPackageProvider
.readZipFile(childPath));
} else {
packages.addAll(ClasspathPackageProvider
.readDirectory(childPath));
}
}
}
}
return packages;
}
public static Set<String> readDirectory(String path) {
Set<String> packages = new HashSet<String>();
File file = new File(path);
int startIndex = path.length() + 1;
for (File child : file.listFiles()) {
recursiveRead(child, startIndex, packages);
}
return packages;
}
public static void recursiveRead(File file, int startIndex, Set<String> packages) {
if (!file.isFile()) {
packages.add(file.getAbsolutePath().substring(startIndex)
.replace(File.separator, "."));
for (File child : file.listFiles()) {
recursiveRead(child, startIndex, packages);
}
}
}
public static Set<String> readZipFile(String path) {
Set<String> packages = new HashSet<String>();
try {
ZipFile zFile = new ZipFile(path);
Enumeration<? extends ZipEntry> entries = zFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
if (!entry.isDirectory()) {
String dirName = new File(entry.getName()).getParent();
if (dirName != null) {
String name = dirName.replace(File.separator, ".");
if (name.endsWith(".")) {
name = name.substring(0, name.length() - 1);
}
packages.add(name);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return packages;
}
}
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.service.packageadmin.ExportedPackage;
import org.osgi.service.packageadmin.PackageAdmin;
import org.osgi.util.tracker.ServiceTracker;
/**
* Computes the list of packages exported by all bundles in an Eclipse
* installation. Don't forget to add "Eclipse-BuddyPolicy: global" to your
* MANIFEST.MF file if you want to access exported packages from all bundles
* (and not just the one this plug-in depends on).
*/
public class EclipsePackageProvider implements PackageProvider {
@Override
public Collection<String> getPackages() {
Set<String> packages = new HashSet<String>();
BundleContext context = Activator.getDefault().getBundle()
.getBundleContext();
Bundle[] bundles = context.getBundles();
PackageAdmin pAdmin = getPackageAdmin(context);
for (Bundle bundle : bundles) {
ExportedPackage[] ePackages = pAdmin.getExportedPackages(bundle);
if (ePackages != null) {
for (ExportedPackage ePackage : ePackages) {
packages.add(ePackage.getName());
}
}
}
return packages;
}
public PackageAdmin getPackageAdmin(BundleContext context) {
ServiceTracker bundleTracker = null;
bundleTracker = new ServiceTracker(context,
PackageAdmin.class.getName(), null);
bundleTracker.open();
return (PackageAdmin) bundleTracker.getService();
}
}
import java.util.Collection;
/**
* Computes the list of packages provided by the bootstrap libraries (e.g., rt.jar)
*/
public class JavaLibraryPackageProvider implements PackageProvider {
@Override
public Collection<String> getPackages() {
String classpath = System.getProperty("sun.boot.class.path");
return ClasspathPackageProvider.getPackageFromClassPath(classpath);
}
}
Copyright (c) 2010, Barthelemy Dagenais All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
- The name of the author may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
import java.util.Collection;
/**
* A package provider computes a list of packages accessible at runtime.
*/
public interface PackageProvider {
Collection<String> getPackages();
}
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* Computes the list of packages accessible by the current class loader. May be useful to detect dynamically generated classes/packages.
*/
public class RuntimePackageProvider implements PackageProvider {
@Override
public Collection<String> getPackages() {
Set<String> packages = new HashSet<String>();
for (Package aPackage : Package.getPackages()) {
packages.add(aPackage.getName());
}
return packages;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment