⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 objectutilities.java

📁 JCommon is a Java class library that is used by JFreeChart, Pentaho Reporting and a few other projec
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
     *          boot loader.
     * @return the classloader, never null.
     * @throws SecurityException if the SecurityManager does not allow to grab
     *                           the context classloader.
     */
    public static ClassLoader getClassLoader(final Class c) {
        final String localClassLoaderSource;
        synchronized(ObjectUtilities.class)
        {
          if (classLoader != null) {
              return classLoader;
          }
          localClassLoaderSource = classLoaderSource;
        }

        if ("ThreadContext".equals(localClassLoaderSource)) {
            final ClassLoader threadLoader = Thread.currentThread().getContextClassLoader();
            if (threadLoader != null) {
                return threadLoader;
            }
        }

        // Context classloader - do not cache ..
        final ClassLoader applicationCL = c.getClassLoader();
        if (applicationCL == null) {
            return ClassLoader.getSystemClassLoader();
        }
        else {
            return applicationCL;
        }
    }


    /**
     * Returns the resource specified by the <strong>absolute</strong> name.
     *
     * @param name the name of the resource
     * @param c    the source class
     * @return the url of the resource or null, if not found.
     */
    public static URL getResource(final String name, final Class c) {
        final ClassLoader cl = getClassLoader(c);
        if (cl == null) {
            return null;
        }
        return cl.getResource(name);
    }

    /**
     * Returns the resource specified by the <strong>relative</strong> name.
     *
     * @param name the name of the resource relative to the given class
     * @param c    the source class
     * @return the url of the resource or null, if not found.
     */
    public static URL getResourceRelative(final String name, final Class c) {
        final ClassLoader cl = getClassLoader(c);
        final String cname = convertName(name, c);
        if (cl == null) {
            return null;
        }
        return cl.getResource(cname);
    }

    /**
     * Transform the class-relative resource name into a global name by
     * appending it to the classes package name. If the name is already a
     * global name (the name starts with a "/"), then the name is returned
     * unchanged.
     *
     * @param name the resource name
     * @param c    the class which the resource is relative to
     * @return the tranformed name.
     */
    private static String convertName(final String name, Class c) {
        if (name.startsWith("/")) {
            // strip leading slash..
            return name.substring(1);
        }

        // we cant work on arrays, so remove them ...
        while (c.isArray()) {
            c = c.getComponentType();
        }
        // extract the package ...
        final String baseName = c.getName();
        final int index = baseName.lastIndexOf('.');
        if (index == -1) {
            return name;
        }

        final String pkgName = baseName.substring(0, index);
        return pkgName.replace('.', '/') + "/" + name;
    }

    /**
     * Returns the inputstream for the resource specified by the
     * <strong>absolute</strong> name.
     *
     * @param name the name of the resource
     * @param context the source class
     * @return the url of the resource or null, if not found.
     */
    public static InputStream getResourceAsStream(final String name,
                                                  final Class context) {
        final URL url = getResource(name, context);
        if (url == null) {
            return null;
        }

        try {
            return url.openStream();
        }
        catch (IOException e) {
            return null;
        }
    }

    /**
     * Returns the inputstream for the resource specified by the
     * <strong>relative</strong> name.
     *
     * @param name the name of the resource relative to the given class
     * @param context the source class
     * @return the url of the resource or null, if not found.
     */
    public static InputStream getResourceRelativeAsStream
        (final String name, final Class context) {
        final URL url = getResourceRelative(name, context);
        if (url == null) {
            return null;
        }

        try {
            return url.openStream();
        }
        catch (IOException e) {
            return null;
        }
    }

    /**
     * Tries to create a new instance of the given class. This is a short cut
     * for the common bean instantiation code.
     *
     * @param className the class name as String, never null.
     * @param source    the source class, from where to get the classloader.
     * @return the instantiated object or null, if an error occured.
     */
    public static Object loadAndInstantiate(final String className,
                                            final Class source) {
        try {
            final ClassLoader loader = getClassLoader(source);
            final Class c = loader.loadClass(className);
            return c.newInstance();
        }
        catch (Exception e) {
            return null;
        }
    }

    /**
     * Tries to create a new instance of the given class. This is a short cut
     * for the common bean instantiation code. This method is a type-safe method
     * and will not instantiate the class unless it is an instance of the given
     * type.
     *
     * @param className the class name as String, never null.
     * @param source    the source class, from where to get the classloader.
     * @param type  the type.
     * @return the instantiated object or null, if an error occurred.
     */
    public static Object loadAndInstantiate(final String className,
                                            final Class source,
                                            final Class type) {
        try {
            final ClassLoader loader = getClassLoader(source);
            final Class c = loader.loadClass(className);
            if (type.isAssignableFrom(c)) {
                return c.newInstance();
            }
        }
        catch (Exception e) {
            return null;
        }
        return null;
    }

    /**
     * Returns <code>true</code> if this is version 1.4 or later of the
     * Java runtime.
     *
     * @return A boolean.
     */
    public static boolean isJDK14() {
        try {
          final ClassLoader loader = getClassLoader(ObjectUtilities.class);
          if (loader != null) {
              try {
                loader.loadClass("java.util.RandomAccess");
                return true;
              }
              catch (ClassNotFoundException e) {
                return false;
              }
              catch(Exception e) {
                // do nothing, but do not crash ...
              }
          }
        }
        catch (Exception e) {
          // cant do anything about it, we have to accept and ignore it ..
        }

        // OK, the quick and dirty, but secure way failed. Lets try it
        // using the standard way.
        try {
            final String version = System.getProperty
                    ("java.vm.specification.version");
            // parse the beast...
            if (version == null) {
                return false;
            }

            String[] versions = parseVersions(version);
            String[] target = new String[]{ "1", "4" };
            return (ArrayUtilities.compareVersionArrays(versions, target) >= 0);
        }
        catch(Exception e) {
            return false;
        }
    }

    private static String[] parseVersions (String version)
    {
      if (version == null)
      {
        return new String[0];
      }

      final ArrayList versions = new ArrayList();
      final StringTokenizer strtok = new StringTokenizer(version, ".");
      while (strtok.hasMoreTokens())
      {
        versions.add (strtok.nextToken());
      }
      return (String[]) versions.toArray(new String[versions.size()]);
    }
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -