2012-06-26 33 views
4

我有一個小測驗,我自己無法解決。 我想構建一個將用java打印自己的源代碼的程序。任何人都知道如何做到這一點? 像這個例子:打印自己的源代碼的Java應用程序

public class SourcePrint { 

    private static final long serialVersionUID = 1L; 

    public void test(){ 
     System.out.println("Hi I'm test"); 

    } 
    public static void main(String[] args) { 
     new SourcePrint().test(); 
    } 

} 

當我們運行此,輸出將是相同的是這樣的:

public class SourcePrint { 

    private static final long serialVersionUID = 1L; 

    public void test(){ 
     System.out.println("Hi I'm test"); 

    } 
    public static void main(String[] args) { 
     new SourcePrint().test(); 
    } 

} 

我不知道如何做到這一點。任何人都知道解決方案或至少提示?這不是反編譯器,測驗製造者告訴我這個提示是「靜態的」。

+0

基內斯一般涉及打印源,而不從自己的源文件,該文件被視爲作弊[中關於這在閱讀問題的種類]。您的解決方案要求是否指定您是否允許這樣做? – yoonsi

回答

3

這裏是可以在Java中使用了奎因的例子:

public class Quine { 

    static String s = "public class Quine { public static void main(String[] args) { char c=34; System.out.println(s+c+s+c+';'+'}'); } static String s="; 

    public static void main(String[] args) { 
     char c = 34; 
     System.out.println(s + c + s + c + ';' + '}'); 
    } 
} 

當然並看似強制性鏈接到維基百科:Wikipedia: Quine。根據該計劃有多大這裏這個環節也可能有一些很好的例子:Java Quine

+0

最後一個鏈接已損壞,請修復。 – GGrec

0
import java.io.*; 
class Source 
{ 
    public static void main(String args[]) 
    { 
     try{ 

      //open the file 
     FileInputStream fstream=new FileInputStream("D://Springs WorkSpace/Testing/src/Source.java");//here pass the own java file name with full path 

      // use DataInputStream to read binary NOT text 
     // DataInputStream in=new DataInputStream(fstream); 

      // 
     BufferedReader br=new BufferedReader(new InputStreamReader(fstream)); 
      //read data line by line from the file 
      String s; 
      while((s = br.readLine()) != null) 
      { 
       System.out.println(s); 
      } 
      in.close(); 
     } 
     catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 
} 
相關問題