View Javadoc

1   package org.apache.maven.surefire;
2   
3   /*
4    * Copyright 2001-2005 The Codehaus.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http:www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  import java.net.URL;
20  import java.net.URLClassLoader;
21  import java.util.HashSet;
22  import java.util.Set;
23  
24  public class IsolatedClassLoader
25      extends URLClassLoader
26  {
27      private ClassLoader parent = ClassLoader.getSystemClassLoader();
28  
29      private Set urls = new HashSet();
30  
31      private boolean childDelegation = true;
32  
33      public IsolatedClassLoader()
34      {
35          super( new URL[0], null );
36      }
37  
38      public IsolatedClassLoader( ClassLoader parent, boolean childDelegation )
39      {
40          super( new URL[0], parent );
41  
42          this.childDelegation = childDelegation;
43      }
44  
45      public IsolatedClassLoader( ClassLoader parent )
46      {
47          super( new URL[0], parent );
48      }
49  
50      public void addURL( URL url )
51      {
52          if ( !urls.contains( url ) )
53          {
54              super.addURL( url );
55          }
56          else
57          {
58              urls.add( url );
59          }
60      }
61  
62      public synchronized Class loadClass( String className )
63          throws ClassNotFoundException
64      {
65          Class c;
66  
67          if( childDelegation )
68          {
69              c = findLoadedClass( className );
70  
71              ClassNotFoundException ex = null;
72  
73              if ( c == null )
74              {
75                  try
76                  {
77                      c = findClass( className );
78                  }
79                  catch ( ClassNotFoundException e )
80                  {
81                      ex = e;
82  
83                      if ( parent != null )
84                      {
85                          c = parent.loadClass( className );
86                      }
87                  }
88              }
89  
90              if ( c == null )
91              {
92                  throw ex;
93              }
94          }
95          else
96          {
97              c = super.loadClass( className );
98          }
99  
100         return c;
101     }
102 }