newInstance in Java

Introduction

newInstance is used to instantiate an instance of a class dynamically. Here is an example written in Scala.

1
2
3
4
5
6
7
8
9
10
11
class Printer() {
def print(): Unit = {
println(s"print something")
}
}
object ScalaTest {
def main(args: Array[String]): Unit = {
val testClass = Class.forName("Printer").newInstance().asInstanceOf[Printer]
testClass.print()
}
}

Output

1
print something

By the way, asInstanceOf[Printer] is used for casting in Scala, it’s just like (Printer) Class.forName("Printer").newInstance() in Java.

What if we want to call Printer’s constructor with arguments? We can use getDeclaredConstructor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Printer(val name: String, val description: String) {
def print(): Unit = {
println(s"product name: $name, description: $description")
}
}
object ScalaTest {
def main(args: Array[String]): Unit = {
val testClass = Class.forName("Printer")
.getDeclaredConstructor(classOf[String], classOf[String])
.newInstance("kindle", "used for reading")
.asInstanceOf[Printer]
testClass.print()
}
}

Output

1
product name: kindle, description: used for reading
Share