简体   繁体   English

通过PlayFramework获取Javassist类

[英]Getting javassist class with playframework

I'm trying to obtain CtClass reference to my model class. 我正在尝试获取对我的模型类的CtClass引用。 I started with simpliest version ClassPool.getDefault().get(className); 我从最简单的版本开始ClassPool.getDefault().get(className); and it worked fine. 而且效果很好。 But only on my machine. 但仅在我的机器上。 It doesn't work on server. 它在服务器上不起作用。

Anyway i think that the version shouldn't work because Playframework stores classes in tmp/classses. 无论如何,我认为该版本不起作用,因为Playframework将类存储在tmp / classes中。 So by now i finished with this version: 所以现在我完成了这个版本:

ClassPool pool = new ClassPool();
pool.appendClassPath(Play.applicationPath + "/tmp/classes");
CtClass cls = pool.get(className);

But i am not sure about this version. 但是我不确定这个版本。 Will it work always? 它会一直工作吗? Are there better options? 有更好的选择吗?

I also tried using ClassClassPath and LoaderClassPath but without any success. 我也尝试使用ClassClassPath和LoaderClassPath,但没有成功。

Usually you should not touch javassist class unless you are writing plugin and need to enhance the application code. 通常,除非您正在编写插件并且需要增强应用程序代码,否则您不应该接触javassist类。 in which case, you will have a MyPluginEnhancer extends play.classloading.enhancers.Enhancer , then you can get the javassist class instance by calling makeClass(ApplicationClass appClass) method. 在这种情况下,您将拥有MyPluginEnhancer extends play.classloading.enhancers.Enhancer ,然后可以通过调用makeClass(ApplicationClass appClass)方法来获取javassist类实例。

For a workable example, please refer to https://github.com/greenlaw110/play-morphia/blob/master/src/play/modules/morphia/MorphiaEnhancer.java . 有关可行的示例,请参阅https://github.com/greenlaw110/play-morphia/blob/master/src/play/modules/morphia/MorphiaEnhancer.java

PS: About play.classloading.enhancers.Enhancer.makeClass method implementation PS:关于play.classloading.enhancers.Enhancer.makeClass方法的实现

/**
 * Construct a javassist CtClass from an application class.
 */
public CtClass makeClass(ApplicationClass applicationClass) throws IOException {
    return classPool.makeClass(new ByteArrayInputStream(applicationClass.enhancedByteCode));
}

Where classPool comes from the following code: 其中classPool来自以下代码:

public Enhancer() {
    this.classPool = newClassPool();
}

public static ClassPool newClassPool() {
    ClassPool classPool = new ClassPool();
    classPool.appendSystemPath();
    classPool.appendClassPath(new LoaderClassPath(Enhancer.class.getClassLoader()));
    classPool.appendClassPath(new ApplicationClassesClasspath());
    return classPool;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM