2011-03-22 78 views
0

我正在Core Java中进行项目,该项目标识两个文件之间的相似性,其中一部分是标识声明的函数长度。我已经尝试了下面的代码来查找给定类中声明的方法。如何查找Java程序中声明的函数的数量

import java.lang.reflect.*; 
import java.io.*; 
import java.lang.String.*; 
public class Method1 { 
    private int f1(
    Object p, int x) throws NullPointerException 
    { 
     if (p == null) 
     throw new NullPointerException(); 
     return x; 
    } 

    public static void main(String args[])throws Exception 
    { 
     try { 
      Class cls = Class.forName("Anu"); 
      int a; 
      Method methlist[]= cls.getDeclaredMethods(); 
      for (int i = 0; i < methlist.length;i++) { 
       Method m = methlist[i]; 
       System.out.println(methlist[i]); 
       System.out.println("name = " + (m.getName()).length()); 

      } 
     } 
     catch (Throwable e) { 
      System.err.println(e); 
     } 
    } 
} 

但我必须找到一个程序的所有类。我是否应该为程序提供输入,因为必须在每个类中标识已声明的方法。次要它只在编译给定类时工作,即给定类存在类文件。 任何人都可以帮助我确定给定程序中声明的方法。

而且我必须确定程序中的注释行,请帮助我。

+0

你是什么意思“宣布在给定的程序方法”?在Java方法在类中声明,以及'getDeclaredMethods()'是你如何让他们使用反射(见[发现关于一个类的方法(http://java.sun.com/developer/technicalArticles/ALT/Reflection /)...这就是代码的来源,对吧?)。 – MarcoS 2011-03-22 16:51:05

回答

0

你需要编写程序来阅读原始代码,因为你不仅可以在那里找到评论。您可以自己解析文本以查找注释和方法签名。

你也许能够给谷歌图书馆至极你做到这一点的帮助。

0

使用JavaCompiler进行类,阅读文件作为字符串,如下执行它:

public class SampleTestCase { 

public static void main(String[] args) { 
    String str = "public class sample {public static void doSomething() {System.out.println(\"Im here\");}}"; 
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>(); 

    SimpleJavaFileObject obj = new SourceString("sample", str); 

    Iterable<? extends JavaFileObject> compilationUnits = Arrays 
      .asList(obj); 
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, 
      null, compilationUnits); 

    boolean success = task.call(); 
    if (success) { 
     try { 
      Method[] declaredMethods = Class.forName("sample") 
        .getDeclaredMethods(); 

      for (Method method : declaredMethods) { 
       System.out.println(method.getName()); 
      } 
     } catch (ClassNotFoundException e) { 
      System.err.println("Class not found: " + e); 
     } 
    } 
} 
} 

class SourceString extends SimpleJavaFileObject { 
final String code; 

SourceString(String name, String code) { 
    super(URI.create("string:///" + name.replace('.', '/') 
      + Kind.SOURCE.extension), Kind.SOURCE); 
    this.code = code; 
} 

@Override 
public CharSequence getCharContent(boolean ignoreEncodingErrors) { 
    return code; 
} 

}