2011-03-22 31 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; 
} 

}