is there a way to intercept new Thread() and instanciate a custom Thread instead

StackOverflow https://stackoverflow.com/questions/16612806

  •  29-05-2022
  •  | 
  •  

Question

I try to generate a code that force the thread to be of my class CustomThread.

Thread myThread=new Thread(myRunnable);
if(myThread instanceOf CustomThread)
{
    System.err.println("ok");
}

I have tried to replace the ClassLoader by my custom ClassLoader that overload findClass(String name) and loadClass(String name) to catch the name java.lang.thread and load my CustomThread class instead, and I set this CustomClassLoader as the classLoader to Create all the object in my thread. in this thread instanciation of String and other Class are handled by the CustomClassLoader but new Thread(isn't).

do someone know if what i want to do is possible and how to do it?

public Class<?> loadClass( String name ) throws ClassNotFoundException
{
            System.err.println( "loadClass name: "+name   );

    if ( name.equals( Thread.class.getName() ) && flagThreadDefine == 0 )
    {
        // Class<?> redifineClass = redefineClass( name );
        flagThreadDefine = 1;
        return redefineClass(CustomThread.class.getName() );
    }
    flagThreadDefine = 0;
    return super.loadClass( name ); 
}
private Class<?> redefineClass( String name )
{
    URL findResource = findResource( name.replace( '.', '/' ).concat( ".class" ) );
    if ( findResource != null )
    {
        try
        {
            URLConnection openConnection = findResource.openConnection();
            InputStream input = openConnection.getInputStream();
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            int data = input.read();

            while ( data != -1 )
            {
                buffer.write( data );
                data = input.read();
            }

            input.close();

            byte[] classData = buffer.toByteArray();

            return defineClass( name, classData, 0, classData.length );
          }
        catch ( IOException ex )
        {
            Logger.getLogger( CustomClassLoader.class.getName() ).log( Level.SEVERE,null, ex );
        }
    }
    return null;

}

ps: sorry for my poor English.

Était-ce utile?

La solution

I would imagine that the Thread class is loaded before any of your custom code gets a chance to execute (seeing as your code is most likely executing on an instance of a Thread).

In order to replace a class like Thread, you would most likely need to create a jar with your custom implementation and put it on the bootclasspath. however, you would need to replace the current implementation not extend it, which makes things trickier.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top