Java/Reflection/Package

Материал из Java эксперт
Перейти к: навигация, поиск

Demonstrates how to get declaration information on a Class

   
/*
 *     file: PackageInfoDemo.java
 *  package: oreilly.hcj.reflection
 *
 * This software is granted under the terms of the Common Public License,
 * CPL, which may be found at the following URL:
 * http://www-124.ibm.ru/developerworks/oss/CPLv1.0.htm
 *
 * Copyright(c) 2003-2005 by the authors indicated in the @author tags.
 * All Rights are Reserved by the various authors.
 *
########## DO NOT EDIT ABOVE THIS LINE ########## */

import java.util.Collection;
/**  
 * Demonstrates how to get declaration information on a Class.
 *
 * @author 
 * @version $Revision: 1.3 $
 */
public class PackageInfoDemo {
  /** 
   * Demonstration Method.
   *
   * @param args Command line arguments.
   */
  public static void main(final String[] args) {
    System.out.println(Object.class.getPackage());
    System.out.println(Float.class.getPackage());
    System.out.println(Collection.class.getPackage());
    System.out.println(int.class.getPackage());
    System.out.println(String.class.getPackage());
  }
}
/* ########## End of File ########## */





Detect if a package is available

   
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;
  }
}





Get all information about a package

   
class PackageInfo {
  public static void main(String[] args) {
    Package p = Package.getPackage("java.lang");
    System.out.println("Name = " + p.getName());
    System.out.println("Implementation title = " + p.getImplementationTitle());
    System.out.println("Implementation vendor = " + p.getImplementationVendor());
    System.out.println("Implementation version = " + p.getImplementationVersion());
    System.out.println("Specification title = " + p.getSpecificationTitle());
    System.out.println("Specification vendor = " + p.getSpecificationVendor());
    System.out.println("Specification version = " + p.getSpecificationVersion());
  }
}





Get full package name

   
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));
  }
}





Get package by name

   
public class Main {
  public static void main(String[] a) {
    Package p = Package.getPackage("java.lang");
    System.out.println("Name = " + p.getName());
    System.out.println("Implementation title = " + p.getImplementationTitle());
    System.out.println("Implementation vendor = " + p.getImplementationVendor());
    System.out.println("Implementation version = " + p.getImplementationVersion());
  }
}
/*Name = java.lang
Implementation title = Java Runtime Environment
Implementation vendor = Sun Microsystems, Inc.
Implementation version = 1.6.0_02
 */





Get package name of a class

   
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);
  }
}





Get Package Names From Dir

 
/**
 * 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("/", ".");
  }
}





getPackage() returns null for a class in the unnamed package

   
public class Main {
  public static void main(String[] argv) throws Exception {
    Class cls = MyClass.class;
    Package pkg = cls.getPackage(); // null
  }
}
class MyClass{}





getPackage() returns null for a primitive type or array

   
public class Main {
  public static void main(String[] argv) throws Exception {
    Package pkg = int.class.getPackage(); // null
    pkg = int[].class.getPackage(); // null
  }
}





Get the class name with or without the package

   
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));
  }
}





Getting the Package of a Class

   
public class Main {
  public static void main(String[] argv) throws Exception {
    Class cls = java.lang.String.class;
    Package pkg = cls.getPackage();
    String name = pkg.getName(); // java.lang
  }
}





Package Utils

  
/**
 * 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.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;

public final class PackageUtils {
    
    private static final Set<String> KEYWORDS = new HashSet<String>(Arrays
        .asList(new String[] {"abstract", "boolean", "break", "byte", "case", "catch", "char", "class",
                              "const", "continue", "default", "do", "double", "else", "extends", "final",
                              "finally", "float", "for", "goto", "if", "implements", "import", "instanceof",
                              "int", "interface", "long", "native", "new", "package", "private", "protected",
                              "public", "return", "short", "static", "strictfp", "super", "switch",
                              "synchronized", "this", "throw", "throws", "transient", "try", "void",
                              "volatile", "while", "true", "false", "null", "assert", "enum"}));
    
    private PackageUtils() {
        
    }
    
    static String getPackageName(String className) {
        int pos = className.lastIndexOf(".");
        if (pos != -1) {
            return className.substring(0, pos);
        } else {
            return "";
        }
    }
    
    public static String getPackageName(Class<?> clazz) {
        String className = clazz.getName();
        if (className.startsWith("[L")) {
            className = className.substring(2);
        }
        return getPackageName(className);
    }
    
    public static String parsePackageName(String namespace, String defaultPackageName) {
        String packageName = (defaultPackageName != null && defaultPackageName.trim().length() > 0)
            ? defaultPackageName : null;
        if (packageName == null) {
            packageName = getPackageNameByNameSpaceURI(namespace);
        }
        return packageName;
    }
    
    public static String getPackageNameByNameSpaceURI(String nameSpaceURI) {
        int idx = nameSpaceURI.indexOf(":");
        String scheme = "";
        if (idx >= 0) {
            scheme = nameSpaceURI.substring(0, idx);
            if ("http".equalsIgnoreCase(scheme) || "urn".equalsIgnoreCase(scheme)) {
                nameSpaceURI = nameSpaceURI.substring(idx + 1);
            }
        }
        List<String> tokens = tokenize(nameSpaceURI, "/: ");
        if (tokens.size() == 0) {
            return null;
        }
        if (tokens.size() > 1) {
            String lastToken = tokens.get(tokens.size() - 1);
            idx = lastToken.lastIndexOf(".");
            if (idx > 0) {
                lastToken = lastToken.substring(0, idx);
                tokens.set(tokens.size() - 1, lastToken);
            }
        }
        String domain = tokens.get(0);
        idx = domain.indexOf(":");
        if (idx >= 0) {
            domain = domain.substring(0, idx);
        }
        List<String> r = reverse(tokenize(domain, "urn".equals(scheme) ? ".-" : "."));
        if ("www".equalsIgnoreCase(r.get(r.size() - 1))) {
            // remove leading www
            r.remove(r.size() - 1);
        }
        // replace the domain name with tokenized items
        tokens.addAll(1, r);
        tokens.remove(0);
        // iterate through the tokens and apply xml->java name algorithm
        for (int i = 0; i < tokens.size(); i++) {
            // get the token and remove illegal chars
            String token = tokens.get(i);
            token = removeIllegalIdentifierChars(token);
            // this will check for reserved keywords
            if (containsReservedKeywords(token)) {
                token = "_" + token;
            }
            tokens.set(i, token.toLowerCase());
        }
        // concat all the pieces and return it
        return combine(tokens, ".");
    }
    private static List<String> tokenize(String str, String sep) {
        StringTokenizer tokens = new StringTokenizer(str, sep);
        List<String> r = new ArrayList<String>();
        while (tokens.hasMoreTokens()) {
            r.add(tokens.nextToken());
        }
        return r;
    }
    private static <T> List<T> reverse(List<T> a) {
        List<T> r = new ArrayList<T>();
        for (int i = a.size() - 1; i >= 0; i--) {
            r.add(a.get(i));
        }
        return r;
    }
    private static String removeIllegalIdentifierChars(String token) {
        StringBuffer newToken = new StringBuffer();
        for (int i = 0; i < token.length(); i++) {
            char c = token.charAt(i);
            if (i == 0 && !Character.isJavaIdentifierStart(c)) {
                // prefix an "_" if the first char is illegal
                newToken.append("_" + c);
            } else if (!Character.isJavaIdentifierPart(c)) {
                // replace the char with an "_" if it is illegal
                newToken.append("_");
            } else {
                // add the legal char
                newToken.append(c);
            }
        }
        return newToken.toString();
    }
    private static String combine(List r, char sep) {
        StringBuilder buf = new StringBuilder(r.get(0).toString());
        for (int i = 1; i < r.size(); i++) {
            buf.append(sep);
            buf.append(r.get(i));
        }
        return buf.toString();
    }
    private static boolean containsReservedKeywords(String token) {
        return KEYWORDS.contains(token);
    }
    public static String getNamespace(String packageName) {
        if (packageName == null || packageName.length() == 0) {
            return null;
        }
        StringTokenizer tokenizer = new StringTokenizer(packageName, ".");
        String[] tokens;
        if (tokenizer.countTokens() == 0) {
            tokens = new String[0];
        } else {
            tokens = new String[tokenizer.countTokens()];
            for (int i = tokenizer.countTokens() - 1; i >= 0; i--) {
                tokens[i] = tokenizer.nextToken();
            }
        }
        StringBuffer namespace = new StringBuffer("http://");
        String dot = "";
        for (int i = 0; i < tokens.length; i++) {
            if (i == 1) {
                dot = ".";
            }
            namespace.append(dot + tokens[i]);
        }
        namespace.append("/");
        return namespace.toString();
    }
    
}





Show the Packages

   
/*
 * Copyright (c) Ian F. Darwin, http://www.darwinsys.ru/, 1996-2002.
 * All rights reserved. Software written by Ian F. Darwin and others.
 * $Id: LICENSE,v 1.8 2004/02/09 03:33:38 ian Exp $
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. 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.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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.
 * 
 * Java, the Duke mascot, and all variants of Sun"s Java "steaming coffee
 * cup" logo are trademarks of Sun Microsystems. Sun"s, and James Gosling"s,
 * pioneering role in inventing and promulgating (and standardizing) the Java 
 * language and environment is gratefully acknowledged.
 * 
 * The pioneering role of Dennis Ritchie and Bjarne Stroustrup, of AT&T, for
 * inventing predecessor languages C and C++ is also gratefully acknowledged.
 */
/**
 * Show the Packages. Requires JDK1.2.
 * @author Ian F. Darwin, http://www.darwinsys.ru/
 * @version $Id: Packages.java,v 1.4 2004/02/09 03:33:51 ian Exp $
 */
public class Packages {
  public static void main(String[] argv) {
    //+
    java.lang.Package[] all = java.lang.Package.getPackages();
    for (int i=0; i<all.length; i++)
      System.out.println(all[i]);
    //-
  }
}