2012-11-15 2 views
0

Java 프로젝트에서 디스크의 파일을 읽었습니다. 내 hohoho.java 파일은 D : /에 있으며 File 형식이므로 주 클래스 (Up.java)가있는 기존 패키지에 클래스로 추가하고 싶습니다. 패키지 -> Up.java, Hohoho.java와 같이 보일 것입니다.프로그래밍 방식으로 프로젝트에 새 클래스 추가

물론 프로그래밍 방식으로 수행해야합니다. 이 .java 파일을 사용하고 Up.java의 함수입니다.

쉬운 방법이 있습니까?

import org.apache.commons.io.FileUtils; 
import java.io.File; 
import java.lang.reflect.Array; 
import java.util.Collection; 
import java.util.Iterator; 

public class Up{ 

public static void main(String[] args) { 

    File root = new File("..\\."); 
    File myfile = null; 

    try { 

     String[] extensions = {"java"}; 
     boolean recursive = true; 

     Collection files = FileUtils.listFiles(root, extensions, recursive); 

     for (Iterator iterator = files.iterator(); iterator.hasNext();) { 
      File file = (File) iterator.next(); 
      String path = file.getAbsolutePath(); 
      System.out.println("File = " + path); 

      String[] tokens = path.split("\\\\"); 

      for (String t : tokens) 
       if (t.equals("Hohoho.java")){ 
        myfile = file; 
       } 
      } 

     System.out.println("Client class: " + myfile.getAbsolutePath()); 

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

    } 
} 
+2

그래이 프로그래밍 방식으로 수행 할 수 있지만, 당신은 당신이 코드의 도요새를 제출할 수 시나리오 –

+2

정교한하면 더 편리 할 것입니다 그래서 우리는 당신을 위해 그것을 완료 할 수 있습니까? –

+1

'java' 파일이라면 컴파일러를 호출해야합니다. 그것이'class' 파일이라면 조금 쉽지만 여전히 관련이 있습니다. –

답변

1

필요하고 의 .class 파일은, 당신의 의견에 따라, 당신은 단지이 다음 (사용자의 설정에 어떤 보안 문제 없다고 가정) 같은 것을 사용할 수 있어야합니다 :

String path = "/path/to/your/classfiles/root/"; //not including the package structure 
    ClassLoader loader = new URLClassLoader(new URL[]{new URL("file://" + path)}, Up.class.getClassLoader()); 

    Class clazz = loader.loadClass("foo.Hohoho"); //assuming a package "foo" for that class 
    Object loadable = clazz.newInstance(); 
    Field field = loadable.getClass().getField("someField"); //or whatever - (this assumes you have someField on foo.Hohoho) 

    System.out.println(field.get(loadable)); 

(나는 위의에서 처리하는 모든 예외를 떨어). @stemm이 지적했듯이, 이것은 pure Reflection을 사용하는 것만으로도 고통 스러울 것입니다.

또한 VM 내에서 가능한 최소한 복잡한 방법으로 Java 컴파일러를 호출하는 빠른 테스트가 뒤 따른다. 당신이 소스에서 이동해야 할 경우 경우에 따라서, 당신은 떨어져 구축 할 수 있습니다이 :

String sourcePath = "/path/to/your/javafiles/root/"; 
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); 
    int success = compiler.run(null, null, null, sourcePath + "foo/Loadable.java");//can't get "-sourcepath","path" to go, for some reason. 

    System.out.println("success = " + success); //should be 0; Sys err should have details, otherwise 
1

Java Compiler API을 사용하여 소스 코드를 바이트 코드로 컴파일하십시오.

그런 다음 ClassLoader을 사용하여 컴파일 된 클래스를 jvm으로로드하면 해당 클래스의 메소드를 실행할 수 있습니다. 당신이 확실하면

는 컴파일 된 클래스는 특정 인터페이스를 구현 - 당신이 직접 인터페이스 및 호출 방법을 목표로 캐스팅 할 수 있습니다, 그렇지 않으면 - 당신은 단지로드해야 할 경우 사용 Reflection

관련 문제