Mega Code Archive

 
Categories / Java / Reflection
 

Force the given class to be loaded fully

import java.lang.reflect.Method; import java.lang.reflect.Modifier; 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 {   /**    * Force the given class to be loaded fully.    *     * <p>    * This method attempts to locate a static method on the given class the    * attempts to invoke it with dummy arguments in the hope that the virtual    * machine will prepare the class for the method call and call all of the    * static class initializers.    *     * @param type    *          Class to force load.    *     * @throws NullArgumentException    *           Type is <i>null</i>.    */   public static void forceLoad(final Class type) {     if (type == null)       System.out.println("Null Argument Exception");     // don't attempt to force primitives to load     if (type.isPrimitive())       return;     // don't attempt to force java.* classes to load     String packageName = Classes.getPackageName(type);     // System.out.println("package name: " + packageName);     if (packageName.startsWith("java.") || packageName.startsWith("javax.")) {       return;     }     // System.out.println("forcing class to load: " + type);     try {       Method methods[] = type.getDeclaredMethods();       Method method = null;       for (int i = 0; i < methods.length; i++) {         int modifiers = methods[i].getModifiers();         if (Modifier.isStatic(modifiers)) {           method = methods[i];           break;         }       }       if (method != null) {         method.invoke(null, (Object[]) null);       } else {         type.newInstance();       }     } catch (Exception ignore) {       ignore.printStackTrace();     }   } }