Java中的`instanceof`在Javassist中的类似实现

huangapple go评论78阅读模式
英文:

Java instanceOf analogue in Javassist

问题

我正在为 Android 项目中的 Gradle 插件进行开发。我使用 Transformation Api 在编译过程中操作字节码,为此我选择了 Javassist。我的问题与这个库有关。在操作字节码之前,我需要确定这个类是哪种类型。例如,如果某个 ctClass 有方法 setOnClickListener(),我想知道它的类型(由 CtClass 表示的类的类型)。可能是 ctClass.instanceOf(android.view.View) 或者 ctClass.instanceOf(android.view.ViewGroup)。我发现了 .toClass() 方法,但它会抛出 InvocationTargetException,我认为它对我来说是不必要的工作。

英文:

I'm working on a plugin for Gradle in android project. I use Transformation Api for manipulate with byte code across compilation and for this purpose I choosen Javassist. My question related to this library. Before manipulate byte code I need determine which type has this class. For example, if some ctClass has method setOnClickListener(), I want to know its type (type of class which represented by CtClass). May be ctClass.instanceOf(android.view.View) or ctClass.instanceOf(android.view.ViewGroup). I found method .toClass() but it throws InvocationTargetException and I think it does unnecessary work for me

答案1

得分: 1

CtClass对象通常通过ClassPool.get("classname")来获取,表示所选类的类文件,该类是通过"classname"获取的。它基本上代表对象本身,而不是该对象的实例。

因此,它不是一个实例化的对象,找出它是哪个"实例"是没有意义的。

然而,如果您需要关于类层次结构的信息,您可以使用CtClass公开的许多方法。这里只举几个例子:

英文:

The CtClass object is usually obtained using ClassPool.get("classname") and represented the class file of the class you selected to get through the "classname". It basically represents the object itself, not an instance of that object.

Therefore it is not an instantiated object and finding out which "instance" it is does not make sense.

However if you need information about the class hierarchy you can use a lot of methods exposed by the CtClass. Here just a couple of examples:

  • getSuperclass() - obtains the class object representing the superclass of the class
  • getInterfaces() - obtains the class objects representing the interfaces implemented by the class

huangapple
  • 本文由 发表于 2020年10月7日 20:30:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/64244084.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定