Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/*
 * Copyright 2007-2011 Hidekatsu Izuno
 *
 * Licensed 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.LinkedHashMap;
import java.util.Map;
import java.util.WeakHashMap;

public class Main {
    private static final Map<ClassLoader, Map<String, Class<?>>> cache = new WeakHashMap<ClassLoader, Map<String, Class<?>>>();

    public static Class<?> findClass(String name) {
        ClassLoader cl;
        try {
            cl = Thread.currentThread().getContextClassLoader();
        } catch (SecurityException e) {
            cl = null;
        }

        Map<String, Class<?>> map;
        synchronized (cache) {
            map = cache.get(cl);

            if (map == null) {
                map = new LinkedHashMap<String, Class<?>>(16, 0.75f, true) {
                    private static final long serialVersionUID = 1L;

                    protected boolean removeEldestEntry(Map.Entry<String, Class<?>> eldest) {
                        return size() > 1024;
                    };
                };
                cache.put(cl, map);
            }
        }
        synchronized (map) {
            if (!map.containsKey(name)) {
                Class<?> target;
                try {
                    if (cl != null) {
                        target = cl.loadClass(name);
                    } else {
                        target = Class.forName(name);
                    }
                } catch (ClassNotFoundException e) {
                    target = null;
                }
                map.put(name, target);
            }
            return map.get(name);
        }
    }
}