summaryrefslogtreecommitdiff
path: root/src/compiler/scala/tools/nsc/ObjectRunner.scala
blob: d2202f5046a4ddb8ab4dda498640bdfd8c92603a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/* NSC -- new Scala compiler
 * Copyright 2005-2006 LAMP/EPFL
 * @author  Lex Spoon
 */

// $Id$

package scala.tools.nsc

import java.io.File
import java.lang.reflect.{Method,Modifier}
import java.net.URLClassLoader

/** An object that runs another object specified by name. */
object ObjectRunner {

  def isMainMethod(meth: Method): Boolean = {
    def paramsOK(params: Array[Class]): Boolean =
      params.length == 1 &&
      params(0) == classOf[Array[String]]
    meth.getName == "main" &&
    Modifier.isStatic(meth.getModifiers) &&
    paramsOK(meth.getParameterTypes)
  }

  def run(
      classpath: List[String],
      objectName: String,
      arguments: Seq[String]): Unit =
    try {
      val classpathURLs = classpath.map(s => new File(s).toURL).toArray
      val mainLoader = new URLClassLoader(classpathURLs, null)
      val clsToRun = Class.forName(objectName, true, mainLoader)

      val method = clsToRun.getMethods.find(isMainMethod) match {
        case Some(meth) =>
          meth
        case None =>
          throw new Error("no main method in object " + objectName)
      }
      val res = method.invoke(null, List(arguments.toArray).toArray)
      ()
    } catch {
      case e: Exception =>
        // ClassNotFoundException, InvocationTargetException, ..
        Console.println(e)
        exit(1)
    }

}