Francesco Devittori said:
Do someone with some experience with classLoaders thinks this
is possible? If yes, how difficult would it be?
I have nearly no knowledge about class loaders and nearly no
experience with tem, but recently I hacked together something
like this. - Not exactly the same as you require: It does
not use two names, but two class loaders.
Beware! The following example does not follow style rules for
writing good class loaders!
I wanted to show how to create two "instances" of a class with
static entries:
public class Scan { static int i = 0; public static int get(){ return i++; }}
So here I go, creating two "instances":
public class Main
{ public static void main( java.lang.String[] args ) throws java.lang.Exception
{ final java.lang.Class instance1 = new ScanLoader().loadClass( "Scan" );
final java.lang.Class instance2 = new ScanLoader().loadClass( "Scan" );
final java.lang.Class[] c = new java.lang.Class[]{};
final java.lang.Object[] o = new java.lang.Object[]{};
java.lang.System.out.println( instance1.getMethod( "get", c ).invoke( null, o ));
java.lang.System.out.println( instance1.getMethod( "get", c ).invoke( null, o ));
java.lang.System.out.println( instance2.getMethod( "get", c ).invoke( null, o ));
java.lang.System.out.println( instance2.getMethod( "get", c ).invoke( null, o )); }}
They can count indepently of each other, as the
output shows:
0
1
0
1
And here is my custom class loader hack:
class ScanLoader extends ClassLoader
{ public ScanLoader()
{ super( ScanLoader.class.getClassLoader() ); }
public java.lang.Class<?> loadClass( final java.lang.String className )
throws ClassNotFoundException
{ return findClass( className ); }
public java.lang.Class<?> findClass( final java.lang.String className )
{ byte classByte[];
java.lang.Class<?> result = null;
if( "java.lang.Object".equals( className ))return java.lang.Object.class;
try
{ java.lang.String classPath =
(( java.lang.String )ClassLoader.getSystemResource
( className.replace( '.', java.io.File.separatorChar ) + ".class" ).getFile() ).
substring( 1 );
classByte = loadClassData( classPath );
result = defineClass( className, classByte, 0, classByte.length, null );
return result; }
catch( final java.lang.Exception e ){ throw new java.lang.RuntimeException(e); }}
private byte[] loadClassData
( final java.lang.String className )
throws java.io.IOException
{ final java.io.File f = new java.io.File( className );
final int size =( int )f.length();
final byte buff[] = new byte[ size ];
{ java.io.FileInputStream fis = new java.io.FileInputStream( f );
{ java.io.DataInputStream dis = new java.io.DataInputStream( fis );
dis.readFully( buff );
dis.close(); }}
return buff; }}