Java - creating a subclass dynamically

前端 未结 3 1794
情话喂你
情话喂你 2021-02-14 09:25

I\'d like to create a subclass programatically. I guess I have few options - Javassist, CGLib, BCEL, or ASM.

The use case is that one app\'s internals are class-oriented

3条回答
  •  爱一瞬间的悲伤
    2021-02-14 09:57

    It's quite easy with Javassist:

    import javassist.CannotCompileException;
    import javassist.ClassPool;
    import javassist.CtClass;
    import javassist.NotFoundException;
    
    static Class createClass( String fullName )
            throws NotFoundException, CannotCompileException
    {
        ClassPool pool = ClassPool.getDefault();
    
        // Create the class.
        CtClass subClass = pool.makeClass( fullName );
        final CtClass superClass = pool.get( DefinitionBasedMigrator.class.getName() );
        subClass.setSuperclass( superClass );
        subClass.setModifiers( Modifier.PUBLIC );
    
        // Add a constructor which will call super( ... );
        CtClass[] params = new CtClass[]{
            pool.get( MigratorDefinition.class.getName() ),
            pool.get( GlobalConfiguration.class.getName()) 
        };
        final CtConstructor ctor = CtNewConstructor.make( params, null, CtNewConstructor.PASS_PARAMS, null, null, subClass );
        subClass.addConstructor( ctor );
    
        return subClass.toClass();
    }
    

    Maven dependency:

    
    
        org.javassist
        javassist
        3.22.0-GA
    
    

提交回复
热议问题