使用特定的ClassLoader获取CtClass [英] get CtClass using specific ClassLoader

查看:171
本文介绍了使用特定的ClassLoader获取CtClass的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的类结构:

I have a class structure like this:

package com.mydomain.myproject;
public class Outer{
    public class Inner{
        //some code
    }
}

现在,我可以使用以下方法获取内部类的 CtClass :

Now, I can get a CtClass of the inner class using:

ClassPool pool=ClassPool.getDefault();
CtClass innerCt=pool.getCtClass("com.mydomain.myproject.Outer$Inner");

如果这些类由特殊的 ClassLoader 加载,则会出现问题.

The problem occurs if those classes are loaded by a special ClassLoader.

ClassPool#getCtClass 失败,因为它使用的 ClassLoader 不知道该类.

ClassPool#getCtClass fails because the ClassLoader it uses doesn't know of the class.

我收到以下异常:

javassist.NotFoundException: io.github.jdiscordbots.nightdream.commands.Eval$Sandbox
    at javassist.ClassPool.get(ClassPool.java:430)
    at javassist.ClassPool.getCtClass(ClassPool.java:495)
    at <my classes>

如何为 ClassPool#getCtClass 指定 ClassLoader ?我可以以某种方式设置 ClassPool 的类加载器吗?我注意到有一个 getClassLoader()方法,但似乎没有设置方法.

How can I specify the ClassLoader for ClassPool#getCtClass? Can I somehow set the class loader of the ClassPool? I noticed that there is a getClassLoader() method but there doesn't seem to be a setter.

推荐答案

ClassPool 支持插入,附加和删除 ClassPath .可以以String或ClassPath实现的形式插入和添加ClassPath.仅以ClassPath的形式支持删除.

ClassPool supports inserting, appending and removing ClassPaths. The ClassPath can be inserted and added in the form of a String or a ClassPath implementation. Removals are only supported in the form of a ClassPath.

提供了4种ClassPath实现:

There are 4 supplied implementations of ClassPath:

  1. ByteArrayClassPath:提供字节码和类名
  2. ClassClassPath:提供Java类
  3. LoaderClassPath:提供一个类加载器
  4. URLClassPath:提供一个URL

这篇关于使用特定的ClassLoader获取CtClass的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆