Java Tutorial/Reflection/Package
Содержание
- 1 Demonstrate Package
- 2 Detect if a package is available
- 3 Find the Package of an Object
- 4 Get full package name
- 5 Get non Package Qualified Name
- 6 Get package name of a class
- 7 Get Package Names From Dir
- 8 getPackage() returns null for a class in the unnamed package
- 9 getPackage() returns null for a primitive type or array
- 10 Get the class name with or without the package
- 11 Get the package name of the specified class.
- 12 Get the short name of the specified class by striping off the package name.
- 13 Returns the package portion of the specified class
Demonstrate Package
<source lang="java">
class PkgTest {
public static void main(String args[]) { Package pkgs[]; pkgs = Package.getPackages(); for(int i=0; i < pkgs.length; i++) System.out.println( pkgs[i].getName() + " " + pkgs[i].getImplementationTitle() + " " + pkgs[i].getImplementationVendor() + " " + pkgs[i].getImplementationVersion() ); }
}</source>
Detect if a package is available
<source lang="java">
public class Main{
public static void main(String args[]) { System.out.println(isAvailable("javax.swing.JComponent")); } public static boolean isAvailable(String className) { boolean isFound = false; try { Class.forName(className, false, null); isFound = true; } catch (ClassNotFoundException e) { isFound = false; } return isFound; }
}</source>
Find the Package of an Object
<source lang="java">
import java.util.ArrayList; import java.util.Vector; public class Main {
public static void main(String[] args) { System.out.println(new Vector().getClass().getPackage().getName()); System.out.println(new ArrayList().getClass().getPackage().getName()); System.out.println("Test String".getClass().getPackage().getName()); System.out.println(new Integer(1).getClass().getPackage().getName()); }
} /* java.util java.util java.lang java.lang
- /</source>
Get full package name
<source lang="java">
public class Main {
public static String getPackageName(Class c) { String fullyQualifiedName = c.getName(); int lastDot = fullyQualifiedName.lastIndexOf("."); if (lastDot == -1) { return ""; } return fullyQualifiedName.substring(0, lastDot); } public static void main(String[] args) { System.out.println(getPackageName(java.awt.Frame.class)); }
}</source>
Get non Package Qualified Name
<source lang="java">
public class Utils {
public static String nonPackageQualifiedName( final Class<?> clazz ) { String name = clazz.getName(); return name.substring(name.lastIndexOf(".") + 1); }
}</source>
Get package name of a class
<source lang="java">
import java.util.Date; public class Main {
public static void main(String[] args) { Date date = new Date(); Package pack = date.getClass().getPackage(); String packageName = pack.getName(); System.out.println("Package Name = " + packageName); }
}</source>
Get Package Names From Dir
<source lang="java">
/**
* Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */
import java.io.File; import java.util.List; public final class ReflectionUtil {
private static void getPackageNamesFromDir(File base, File dir, List<String> pkgs) { boolean foundClass = false; for (File file : dir.listFiles()) { if (file.isDirectory()) { getPackageNamesFromDir(base, file, pkgs); } else if (!foundClass && file.getName().endsWith(".class")) { foundClass = true; String pkg = ""; file = dir; while (!file.equals(base)) { if (!"".equals(pkg)) { pkg = "." + pkg; } pkg = file.getName() + pkg; file = file.getParentFile(); } if (!pkgs.contains(pkg)) { pkgs.add(pkg); } } } } private static String getPackageName(String clzName) { if (clzName.indexOf("/") == -1) { return null; } String packageName = clzName.substring(0, clzName.lastIndexOf("/")); return packageName.replace("/", "."); }
}</source>
getPackage() returns null for a class in the unnamed package
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Class cls = MyClass.class; Package pkg = cls.getPackage(); // null }
} class MyClass{}</source>
getPackage() returns null for a primitive type or array
<source lang="java">
public class Main {
public static void main(String[] argv) throws Exception { Package pkg = int.class.getPackage(); // null pkg = int[].class.getPackage(); // null }
}</source>
Get the class name with or without the package
<source lang="java">
public class Main {
public static String getClassName(Class c) { String className = c.getName(); int firstChar; firstChar = className.lastIndexOf(".") + 1; if (firstChar > 0) { className = className.substring(firstChar); } return className; }
public static void main(String[] args) { System.out.println(getClassName(java.awt.Frame.class)); }
}</source>
Get the package name of the specified class.
<source lang="java">
import java.lang.reflect.Method; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.HashSet; import java.util.List; import java.util.Set; /*
* JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
public class Main {
/** The string used to separator packages */ public static final String PACKAGE_SEPARATOR = "."; /** * Get the package name of the specified class. * * @param classname * Class name. * @return Package name or "" if the classname is in the default * package. * * @throws EmptyStringException * Classname is an empty string. */ public static String getPackageName(final String classname) { if (classname.length() == 0) System.out.println("Empty String Exception"); int index = classname.lastIndexOf(PACKAGE_SEPARATOR); if (index != -1) return classname.substring(0, index); return ""; }
}</source>
Get the short name of the specified class by striping off the package name.
<source lang="java">
import java.lang.reflect.Method; import java.net.URL; import java.security.CodeSource; import java.security.ProtectionDomain; import java.util.HashSet; import java.util.List; import java.util.Set; /*
* JBoss, Home of Professional Open Source * Copyright 2005, JBoss Inc., and individual contributors as indicated * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */
public class Main {
/** The string used to separator packages */ public static final String PACKAGE_SEPARATOR = "."; /** * Get the short name of the specified class by striping off the package name. * * @param classname * Class name. * @return Short class name. */ public static String stripPackageName(final String classname) { int idx = classname.lastIndexOf(PACKAGE_SEPARATOR); if (idx != -1) return classname.substring(idx + 1, classname.length()); return classname; }
}</source>
Returns the package portion of the specified class
<source lang="java">
public class Utils {
/** * Returns the package portion of the specified class * @param className the name of the class from which to extract the package * @return package portion of the specified class */ public static String getPackageName(final String className) { if (className != null) { final int index = className.lastIndexOf("."); return ((index != -1) ? className.substring(0, index) : ""); // NOI18N } return null; }
}</source>