Java Reference
In-Depth Information
Declared Methods for com.jdojo.reflection.Person
public String toString()
public Object clone()
public String getName()
public int getId()
public void setName(String arg0)
Reflecting on Constructors
Getting information about constructors of a class is similar to getting information about a method of a class.
The following four methods in the Class class can be used to get information about the constructors represented
by a Class object:
Constructor[] getConstructors()
Constructor[] getDeclaredConstructors()
Constructor<T> getConstructor(Class... parameterTypes)
Constructor<T> getDeclaredConstructor(Class... parameterTypes)
The getConstructors() method returns all public constructors. The getDeclaredConstructors() method
returns all declared constructors. The other two methods, the getConstructor() and getDeclaredConstructor() ,
are used to get the Constructor object if you know the parameter types of the constructor. Listing 3-8 illustrates how
to get information for the constructors represented by a Class object.
Listing 3-8. Reflecting on Constructors of a Class
// ConstructorReflection.java
package com.jdojo.reflection;
import java.lang.reflect.Constructor;
import java.util.ArrayList;
public class ConstructorReflection {
public static void main(String[] args) {
Class<Person> c = Person.class;
// Get the declared constructors
System.out.println("Constructors for " + c.getName());
Constructor[] constructors = c.getConstructors();
ArrayList<String> constructDescList = getConstructorsDesciption(constructors);
for (String desc : constructDescList) {
System.out.println(desc);
}
}
public static ArrayList<String> getConstructorsDesciption(Constructor[] constructors) {
ArrayList<String> constructorList = new ArrayList<>();
for (Constructor constructor : constructors) {
String modifiers = ExecutableUtil.getModifiers(constructor);
 
Search WWH ::




Custom Search