Java get all constructors

AVAJAVA Web Tutorials

In JavaSW, if you have a Class object for a particular class, you can obtain its public constructors by calling the getConstructors() method on the class object. If you’d like to get all the constructors (public, protected, and private) of a class, you can call getDeclaredConstructors() on the class object. These methods are demonstrated in the ClassConstructorTest example below.

ClassConstructorTest gets a Class object for the ConstructorTest class. It calls getConstructors() and iterates over the resulting Constructor array of public constructors. ClassConstructorTest then calls getDeclaredConstructors() and iterates over the Constructor array of public, protected, and private constructors.

ClassConstructorTest.java

package test; import java.lang.reflect.Constructor; public class ClassConstructorTest < public static void main(String args[]) throws Exception < Class ctClass = ConstructorTest.class; Constructor[] constructors = ctClass.getConstructors(); for (int i = 0; i < constructors.length; i++) < System.out.println("constuctor: " + constructors[i]); > Constructor[] declaredConstructors = ctClass.getDeclaredConstructors(); for (int i = 0; i < declaredConstructors.length; i++) < System.out.println("declared constructor: " + declaredConstructors[i]); > > >

The simple ConstructorTest class is shown below.

ConstructorTest.java

package test; public class ConstructorTest < private String pri; protected String pro; public String pub; private ConstructorTest() < >public ConstructorTest(String pri, String pro, String pub) < this.pri = pri; this.pro = pro; this.pub = pub; > public String getPri() < return pri; > public void setPri(String pri) < this.pri = pri; > public String getPro() < return pro; > public void setPro(String pro) < this.pro = pro; > public String getPub() < return pub; > public void setPub(String pub) < this.pub = pub; > >

If we execute the ClassConstructorTest class, we see the following:

constuctor: public test.ConstructorTest(java.lang.String,java.lang.String,java.lang.String) declared constructor: public test.ConstructorTest(java.lang.String,java.lang.String,java.lang.String) declared constructor: private test.ConstructorTest()

As you can see, getConstructors() retrieves an array of public Constructor objects for a particular class, while getDeclaredConstructors() retrieves an array of public, protected, and private Constructor objects.

Читайте также:  Python intermediate что это

Источник

Get all Constructors in Java

The method java.lang.Class.getConstructors() can be used to return an array that has all the constructor objects that correspond to the public constructors of the class that are represented by the object of the class.

A program that demonstrates this is given as follows −

Example

package Test; import java.lang.reflect.*; public class Demo < public static void main(String[] args) < try < System.out.println("String Constructors are:"); Constructor c[] = String.class.getConstructors(); for(int i = 0; i < c.length; i++) < System.out.println(c[i]); >> catch (Exception e) < System.out.println(e); >> >

Output

String Constructors are: public java.lang.String(byte[],int,int) public java.lang.String(byte[],java.nio.charset.Charset) public java.lang.String(byte[],java.lang.String) throws java.io.UnsupportedEncodingException public java.lang.String(byte[],int,int,java.nio.charset.Charset) public java.lang.String(byte[],int,int,java.lang.String) throws java.io.UnsupportedEncodingException public java.lang.String(java.lang.StringBuilder) public java.lang.String(java.lang.StringBuffer) public java.lang.String(byte[]) public java.lang.String(int[],int,int) java.lang.String() public java.lang.String(char[]) public java.lang.String(java.lang.String) public java.lang.String(char[],int,int) public java.lang.String(byte[],int) public java.lang.String(byte[],int,int,int)

Now let us understand the above program.

The method getConstructors() is used to obtain all the constructors of the String class. These constructors are stored in the array c[] and then displayed using a for loop. A code snippet which demonstrates this is as follows −

System.out.println(«String Constructors are:»); Constructor c[] = String.class.getConstructors(); for(int i = 0; i

Источник

Finding Constructors

A constructor declaration includes the name, modifiers, parameters, and list of throwable exceptions. The java.lang.reflect.Constructor class provides a way to obtain this information.

The ConstructorSift example illustrates how to search a class’s declared constructors for one which has a parameter of a given type.

import java.lang.reflect.Constructor; import java.lang.reflect.Type; import static java.lang.System.out; public class ConstructorSift < public static void main(String. args) < try < ClasscArg = Class.forName(args[1]); Class c = Class.forName(args[0]); Constructor[] allConstructors = c.getDeclaredConstructors(); for (Constructor ctor : allConstructors) < Class[] pType = ctor.getParameterTypes(); for (int i = 0; i < pType.length; i++) < if (pType[i].equals(cArg)) < out.format("%s%n", ctor.toGenericString()); Type[] gpType = ctor.getGenericParameterTypes(); for (int j = 0; j < gpType.length; j++) < char ch = (pType[j].equals(cArg) ? '*' : ' '); out.format("%7c%s[%d]: %s%n", ch, "GenericParameterType", j, gpType[j]); >break; > > > // production code should handle this exception more gracefully > catch (ClassNotFoundException x) < x.printStackTrace(); >> >

Method.getGenericParameterTypes() will consult the Signature Attribute in the class file if it’s present. If the attribute isn’t available, it falls back on Method.getParameterType() which was not changed by the introduction of generics. The other methods with name getGenericFoo() for some value of Foo in reflection are implemented similarly. The syntax for the returned values of Method.get*Types() is described in Class.getName() .

Читайте также:  How to get all elements in javascript

Here is the output for all constructors in java.util.Formatter which have a Locale argument.

$ java ConstructorSift java.util.Formatter java.util.Locale public java.util.Formatter(java.io.OutputStream,java.lang.String,java.util.Locale) throws java.io.UnsupportedEncodingException GenericParameterType[0]: class java.io.OutputStream GenericParameterType[1]: class java.lang.String *GenericParameterType[2]: class java.util.Locale public java.util.Formatter(java.lang.String,java.lang.String,java.util.Locale) throws java.io.FileNotFoundException,java.io.UnsupportedEncodingException GenericParameterType[0]: class java.lang.String GenericParameterType[1]: class java.lang.String *GenericParameterType[2]: class java.util.Locale public java.util.Formatter(java.lang.Appendable,java.util.Locale) GenericParameterType[0]: interface java.lang.Appendable *GenericParameterType[1]: class java.util.Locale public java.util.Formatter(java.util.Locale) *GenericParameterType[0]: class java.util.Locale public java.util.Formatter(java.io.File,java.lang.String,java.util.Locale) throws java.io.FileNotFoundException,java.io.UnsupportedEncodingException GenericParameterType[0]: class java.io.File GenericParameterType[1]: class java.lang.String *GenericParameterType[2]: class java.util.Locale

The next example output illustrates how to search for a parameter of type char[] in String .

$ java ConstructorSift java.lang.String "[C" java.lang.String(int,int,char[]) GenericParameterType[0]: int GenericParameterType[1]: int *GenericParameterType[2]: class [C public java.lang.String(char[],int,int) *GenericParameterType[0]: class [C GenericParameterType[1]: int GenericParameterType[2]: int public java.lang.String(char[]) *GenericParameterType[0]: class [C

The syntax for expressing arrays of reference and primitive types acceptable to Class.forName() is described in Class.getName() . Note that the first listed constructor is package-private , not public . It is returned because the example code uses Class.getDeclaredConstructors() rather than Class.getConstructors() , which returns only public constructors.

This example shows that searching for arguments of variable arity (which have a variable number of parameters) requires use of array syntax:

$ java ConstructorSift java.lang.ProcessBuilder "[Ljava.lang.String;" public java.lang.ProcessBuilder(java.lang.String[]) *GenericParameterType[0]: class [Ljava.lang.String;

This is the actual declaration of the ProcessBuilder constructor in source code:

public ProcessBuilder(String. command)

The parameter is represented as a single-dimension array of type java.lang.String . This can be distinguished from a parameter that is explicitly an array of java.lang.String by invoking Constructor.isVarArgs() .

The final example reports the output for a constructor which has been declared with a generic parameter type:

$ java ConstructorSift java.util.HashMap java.util.Map public java.util.HashMap(java.util.Map) *GenericParameterType[0]: java.util.Map

Exception types may be retrieved for constructors in a similar way as for methods. See the MethodSpy example described in Obtaining Method Type Information section for further details.

Читайте также:  Решение 23 задания егэ информатика python

Источник

Java.lang.Class.getConstructors() Method

The java.lang.Class.getConstructors() method returns an array containing Constructor objects reflecting all the public constructors of the class represented by this Class object. An array of length 0 is returned if the class has no public constructors, or if the class is an array class, or if the class reflects a primitive type or void.

Declaration

Following is the declaration for java.lang.Class.getConstructors() method

public Constructor[] getConstructors() throws SecurityException

Parameters

Return Value

This method returns the array of Constructor objects representing the public constructors of this class.

Exception

SecurityException − If a security manager, s, is present.

Example

The following example shows the usage of java.lang.Class.getConstructors() method.

package com.tutorialspoint; import java.lang.reflect.*; public class ClassDemo < public static void main(String[] args) < try < Class cls = Class.forName("java.awt.Panel"); System.out.println("Panel Constructors ="); /* returns the array of Constructor objects representing the public constructors of this class */ Constructor c[] = cls.getConstructors(); for(int i = 0; i < c.length; i++) < System.out.println(c[i]); >> catch (Exception e) < System.out.println("Exception: " + e); >> >

Let us compile and run the above program, this will produce the following result −

Panel Constructors = public java.awt.Panel() public java.awt.Panel(java.awt.LayoutManager)

Источник

Оцените статью