Annotations and Reflection
Constructor Lookup
A reflected constructor can create an object when the parameter types are known.
Constructor Lookup
ConstructorLookup.java
import java.lang.reflect.Constructor;
public class ConstructorLookup {
static class Person {
private final String name;
private final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String label() {
return name + ":" + age;
}
}
public static void main(String[] args) throws Exception {
int age = ;
Constructor<Person> constructor =
Person.class.getDeclaredConstructor(String.class, int.class);
Person person = constructor.newInstance("Ada", age);
System.out.println("person=" + person.label());
}
}
import java.lang.reflect.Constructor;
public class ConstructorLookup {
static class Person {
private final String name;
private final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String label() {
return name + ":" + age;
}
}
public static void main(String[] args) throws Exception {
int age = ;
Constructor<Person> constructor =
Person.class.getDeclaredConstructor(String.class, int.class);
Person person = constructor.newInstance("Ada", age);
System.out.println("person=" + person.label());
}
}
import java.lang.reflect.Constructor;
public class ConstructorLookup {
static class Person {
private final String name;
private final int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
String label() {
return name + ":" + age;
}
}
public static void main(String[] args) throws Exception {
int age = ;
Constructor<Person> constructor =
Person.class.getDeclaredConstructor(String.class, int.class);
Person person = constructor.newInstance("Ada", age);
System.out.println("person=" + person.label());
}
}
constructor metadata
A Constructor object describes how to create a class instance.
newInstance
Calling newInstance runs the constructor with the supplied arguments.