java - Javassist: creating an interface that extends another interface with generics -
i using javassist in project , need create following interface @ runtime:
package com.example; import org.springframework.data.repository.crudrepository; import com.example.cat; public interface catrepository extends crudrepository<cat, long> {}
while had no problem creating interface catrepository
extending crudrepository
, not understand (from docs , looking @ source code), how specify com.example.cat
, java.lang.long
generics types super-interface.
please note that:
com.example.cat
: created @ runtime using javassist (no problems that, have tested , worksorg.springframework.data.repository.crudrepository
: existent class library.
if 1 great!
thanks! luca
short answer
the generic information can manipulated in javassist using signatureattribute.
long answer (with code)
the code have this:
classpool defaultclasspool = classpool.getdefault(); ctclass superinterface = defaultclasspool.getctclass(crudrepository.class .getname()); ctclass catrepositoryinterface = defaultclasspool.makeinterface("catrepository", ctclass); // missing here :-( catrepositoryinterface.toclass()
but, said not add information generics. in order achieve same bytecode compiling source code, need following comment is:
signatureattribute signatureattribute = new signatureattribute( classfile.getconstpool(), "ljava/lang/object;lorg/springframework/data/repository/crudrepository<lorg/example/cat;ljava/lang/long;>;"); classfile metainformation = catrepositoryinterface.getclassfile(); classfile.addattribute(signatureattribute);
let's break down signature string in order understand what's happening there:
you see several l[type], it? l standard notation in bytecode define object class, can read more if you're interested in jvm specification regarding descriptors
';' being used separator between several definitions. let's @ each 1 of them:
- ljava/lang/object
- lorg/springframework/data/repository/crudrepository
<lorg/example/cat;ljava/lang/long;>
the first definition has there because in java language extends java.lang.object (doesn't matter if class or interface).
but interesting 1 second one, there have type full classname , generic types definitions, using l notation. that's missing :-)
note
keep in mind if want extend more 1 interface, have add them in list example, following signature make interface not extend crudrepository serializable:
ljava/lang/object;lorg/springframework/data/repository/crudrepository<lorg/example/cat;ljava/lang/long;>;**ljava/io/serializable;**
Comments
Post a Comment