gpt4 book ai didi

java - BCEL - 获取类名、元素名和方法名

转载 作者:行者123 更新时间:2023-12-01 12:20:25 29 4
gpt4 key购买 nike

如何使用bcel classparaser获取类名、元素名和方法名?我已经找到了一种获取类名的方法,但是元素和方法名称给了我一些错误。任何人都可以帮助我吗?这是我的代码(有一些错误,并且未完成):

import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.generic.ConstantPoolGen;

public final class BcelTest
{
// static int methods;

public static void main(String[] args)
{
ClassParser parser;
try
{

JarFile jar = new JarFile("C:\\Users\\OOO\\Desktop\\Sample.Jar");
Enumeration<JarEntry> entries = jar.entries();
ConstantPoolGen cpg = jar.entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
if (!entry.getName().endsWith(".class"))
continue;

parser =
new ClassParser("C:\\Users\\OOO\\Desktop\\Sample.Jar",
entry.getName());
methods = getMethodName(cpg);

MyClassVisitor visitor = new MyClassVisitor(parser.parse());
visitor.start();
}

}
catch (IOException e)
{
e.printStackTrace();
}
}

public String getMethodName(ConstantPoolGen cpg)
{
return getMethodName(cpg);
}
}

最佳答案

您可以在 JavaParser 上调用 parse() 来获取 JavaClass 类,该类提供所有必需的信息:

import java.io.IOException;
import java.util.Enumeration;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.Field;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;

public final class BcelTest
{
public static void main(String[] args)
{
JarFile jar = null;
try
{
String jarName = "C:/theFile.jar";
jar = new JarFile(jarName);
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements())
{
JarEntry entry = entries.nextElement();
if (!entry.getName().endsWith(".class"))
{
continue;
}

ClassParser parser =
new ClassParser(jarName, entry.getName());
JavaClass javaClass = parser.parse();

System.out.println("Class: "+javaClass.getClassName());
System.out.println(" Fields:");
for (Field field : javaClass.getFields())
{
System.out.println(" "+field);
}
System.out.println(" Methods:");
for (Method method : javaClass.getMethods())
{
System.out.println(" "+method);
}
}
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (jar != null)
{
try
{
jar.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
}

关于java - BCEL - 获取类名、元素名和方法名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26702103/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com