Java examples for Reflection:Class
Loads a class from the classloader; If not found, the classloader of the context class specified will be used.
//Licensed under the Apache License, Version 2.0 (the "License"); //package com.java2s; public class Main { public static void main(String[] argv) throws Exception { String className = "java2s.com"; Class context = String.class; boolean checkParent = true; System.out.println(loadClass(className, context, checkParent)); }//from w w w. j ava 2 s.co m /** * Loads a class from the classloader; * If not found, the classloader of the {@code context} class specified will be used. * If the flag {@code checkParent} is true, the classloader's parent is included in * the lookup. */ static Class<?> loadClass(String className, Class<?> context, boolean checkParent) { Class<?> clazz = null; try { clazz = Thread.currentThread().getContextClassLoader() .loadClass(className); } catch (ClassNotFoundException e) { if (context != null) { ClassLoader loader = context.getClassLoader(); while (loader != null) { try { clazz = loader.loadClass(className); return clazz; } catch (ClassNotFoundException e1) { loader = checkParent ? loader.getParent() : null; } } } } return clazz; } }