다음 프로그램은 JAR 파일을 엽니 다 (분명한 이유는 bcel-5.2.jar
입니다 - 어쨌든 필요합니다 ...) 위에서 설명한 방식으로 처리합니다. JAR 파일의 각 JavaClass
의 경우,이 클래스에서 호출하는 Method
의 목록에 참조 된 모든 JavaClass
객체에서지도를 생성하고, 그에 따라 정보를 인쇄합니다, 그러나,
import java.io.IOException;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.bcel.classfile.ClassFormatException;
import org.apache.bcel.classfile.ClassParser;
import org.apache.bcel.classfile.ConstantPool;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ConstantPoolGen;
import org.apache.bcel.generic.Instruction;
import org.apache.bcel.generic.InstructionHandle;
import org.apache.bcel.generic.InstructionList;
import org.apache.bcel.generic.InvokeInstruction;
import org.apache.bcel.generic.MethodGen;
import org.apache.bcel.generic.ObjectType;
import org.apache.bcel.generic.ReferenceType;
import org.apache.bcel.generic.Type;
public class BCELRelationships
{
public static void main(String[] args) throws Exception
{
JarFile jarFile = null;
try
{
String jarName = "bcel-5.2.jar";
jarFile = new JarFile(jarName);
findReferences(jarName, jarFile);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (jarFile != null)
{
try
{
jarFile.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
}
private static void findReferences(String jarName, JarFile jarFile)
throws ClassFormatException, IOException, ClassNotFoundException
{
Map<String, JavaClass> javaClasses =
collectJavaClasses(jarName, jarFile);
for (JavaClass javaClass : javaClasses.values())
{
System.out.println("Class "+javaClass.getClassName());
Map<JavaClass, Set<Method>> references =
computeReferences(javaClass, javaClasses);
for (Entry<JavaClass, Set<Method>> entry : references.entrySet())
{
JavaClass referencedJavaClass = entry.getKey();
Set<Method> methods = entry.getValue();
System.out.println(
" is referencing class "+
referencedJavaClass.getClassName()+" by calling");
for (Method method : methods)
{
System.out.println(
" "+method.getName()+" with arguments "+
Arrays.toString(method.getArgumentTypes()));
}
}
}
}
private static Map<String, JavaClass> collectJavaClasses(
String jarName, JarFile jarFile)
throws ClassFormatException, IOException
{
Map<String, JavaClass> javaClasses =
new LinkedHashMap<String, JavaClass>();
Enumeration<JarEntry> entries = jarFile.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();
javaClasses.put(javaClass.getClassName(), javaClass);
}
return javaClasses;
}
public static Map<JavaClass, Set<Method>> computeReferences(
JavaClass javaClass, Map<String, JavaClass> knownJavaClasses)
throws ClassNotFoundException
{
Map<JavaClass, Set<Method>> references =
new LinkedHashMap<JavaClass, Set<Method>>();
ConstantPool cp = javaClass.getConstantPool();
ConstantPoolGen cpg = new ConstantPoolGen(cp);
for (Method m : javaClass.getMethods())
{
String fullClassName = javaClass.getClassName();
String className =
fullClassName.substring(0, fullClassName.length()-6);
MethodGen mg = new MethodGen(m, className, cpg);
InstructionList il = mg.getInstructionList();
if (il == null)
{
continue;
}
InstructionHandle[] ihs = il.getInstructionHandles();
for(int i=0; i < ihs.length; i++)
{
InstructionHandle ih = ihs[i];
Instruction instruction = ih.getInstruction();
if (!(instruction instanceof InvokeInstruction))
{
continue;
}
InvokeInstruction ii = (InvokeInstruction)instruction;
ReferenceType referenceType = ii.getReferenceType(cpg);
if (!(referenceType instanceof ObjectType))
{
continue;
}
ObjectType objectType = (ObjectType)referenceType;
String referencedClassName = objectType.getClassName();
JavaClass referencedJavaClass =
knownJavaClasses.get(referencedClassName);
if (referencedJavaClass == null)
{
continue;
}
String methodName = ii.getMethodName(cpg);
Type[] argumentTypes = ii.getArgumentTypes(cpg);
Method method =
findMethod(referencedJavaClass, methodName, argumentTypes);
Set<Method> methods = references.get(referencedJavaClass);
if (methods == null)
{
methods = new LinkedHashSet<Method>();
references.put(referencedJavaClass, methods);
}
methods.add(method);
}
}
return references;
}
private static Method findMethod(
JavaClass javaClass, String methodName, Type argumentTypes[])
throws ClassNotFoundException
{
for (Method method : javaClass.getMethods())
{
if (method.getName().equals(methodName))
{
if (Arrays.equals(argumentTypes, method.getArgumentTypes()))
{
return method;
}
}
}
for (JavaClass superClass : javaClass.getSuperClasses())
{
Method method = findMethod(superClass, methodName, argumentTypes);
if (method != null)
{
return method;
}
}
return null;
}
}
참고이 그 모든면에서 정보가 완전하지 않을 수 있습니다. 예를 들어, 다형성으로 인해 다형성 추상화 뒤에 "숨겨져"있기 때문에 메서드가 특정 클래스의 개체에서 호출 된 것을 항상 감지하지는 못할 수 있습니다. 예를 들어, 코드
void call() {
MyClass m = new MyClass();
callToString(m);
}
void callToString(Object object) {
object.toString();
}
toString
에 대한 호출이 실제로 MyClass
의 인스턴스에서 발생 같은 니펫을. 그러나 다형성으로 인해 "some Object
"에 대해서만이 메소드 호출을 인식 할 수 있습니다.