Java reflection constructor with parameters

Java reflection constructor with parameters

Constructor provides information about, and access to, a single constructor for a class. Constructor permits widening conversions to occur when matching the actual parameters to newInstance() with the underlying constructor’s formal parameters, but throws an IllegalArgumentException if a narrowing conversion would occur.

Field Summary

Fields inherited from interface java.lang.reflect.Member

Method Summary

Returns an AnnotatedType object that represents the use of a type to specify the receiver type of the method/constructor represented by this Executable object.

Returns an AnnotatedType object that represents the use of a type to specify the return type of the method/constructor represented by this Executable.

Returns this element’s annotation for the specified type if such an annotation is present, else null.

Returns the Class object representing the class or interface that declares the executable represented by this object.

Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying executable represented by this object.

Returns an array of Type objects that represent the exceptions declared to be thrown by this executable object.

Returns an array of Type objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

Returns an array of arrays of Annotation s that represent the annotations on the formal parameters, in declaration order, of the Executable represented by this object.

Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the executable represented by this object.

Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order.

Returns true if this executable was declared to take a variable number of arguments; returns false otherwise.

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor’s declaring class, with the specified initialization parameters.

Methods inherited from class java.lang.reflect.Executable

Methods inherited from class java.lang.reflect.AccessibleObject

Methods inherited from class java.lang.Object

Methods inherited from interface java.lang.reflect.AnnotatedElement

Method Detail

getDeclaringClass

Returns the Class object representing the class or interface that declares the executable represented by this object.

Читайте также:  Php get data with post

getName

Returns the name of this constructor, as a string. This is the binary name of the constructor’s declaring class.

getModifiers

getTypeParameters

public TypeVariableConstructorT>>[] getTypeParameters()

Returns an array of TypeVariable objects that represent the type variables declared by the generic declaration represented by this GenericDeclaration object, in declaration order. Returns an array of length 0 if the underlying generic declaration declares no type variables.

getParameterTypes

Returns an array of Class objects that represent the formal parameter types, in declaration order, of the executable represented by this object. Returns an array of length 0 if the underlying executable takes no parameters.

getParameterCount

public int getParameterCount()

Returns the number of formal parameters (whether explicitly declared or implicitly declared or neither) for the executable represented by this object.

getGenericParameterTypes

Returns an array of Type objects that represent the formal parameter types, in declaration order, of the executable represented by this object. Returns an array of length 0 if the underlying executable takes no parameters. If a formal parameter type is a parameterized type, the Type object returned for it must accurately reflect the actual type parameters used in the source code. If a formal parameter type is a type variable or a parameterized type, it is created. Otherwise, it is resolved.

getExceptionTypes

Returns an array of Class objects that represent the types of exceptions declared to be thrown by the underlying executable represented by this object. Returns an array of length 0 if the executable declares no exceptions in its throws clause.

getGenericExceptionTypes

Returns an array of Type objects that represent the exceptions declared to be thrown by this executable object. Returns an array of length 0 if the underlying executable declares no exceptions in its throws clause. If an exception type is a type variable or a parameterized type, it is created. Otherwise, it is resolved.

equals

Compares this Constructor against the specified object. Returns true if the objects are the same. Two Constructor objects are the same if they were declared by the same class and have the same formal parameter types.

hashCode

Returns a hashcode for this Constructor . The hashcode is the same as the hashcode for the underlying constructor’s declaring class name.

toString

Returns a string describing this Constructor . The string is formatted as the constructor access modifiers, if any, followed by the fully-qualified name of the declaring class, followed by a parenthesized, comma-separated list of the constructor’s formal parameter types. For example:

public java.util.Hashtable(int,float)

The only possible modifiers for constructors are the access modifiers public , protected or private . Only one of these may appear, or none if the constructor has default (package) access.

Читайте также:  Вывести пустую строку питон

toGenericString

Returns a string describing this Constructor , including type parameters. The string is formatted as the constructor access modifiers, if any, followed by an angle-bracketed comma separated list of the constructor’s type parameters, if any, followed by the fully-qualified name of the declaring class, followed by a parenthesized, comma-separated list of the constructor’s generic formal parameter types. If this constructor was declared to take a variable number of arguments, instead of denoting the last parameter as «Type[]«, it is denoted as «Type. «. A space is used to separate access modifiers from one another and from the type parameters or return type. If there are no type parameters, the type parameter list is elided; if the type parameter list is present, a space separates the list from the class name. If the constructor is declared to throw exceptions, the parameter list is followed by a space, followed by the word » throws » followed by a comma-separated list of the thrown exception types. The only possible modifiers for constructors are the access modifiers public , protected or private . Only one of these may appear, or none if the constructor has default (package) access.

newInstance

public T newInstance(Object. initargs) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException

Uses the constructor represented by this Constructor object to create and initialize a new instance of the constructor’s declaring class, with the specified initialization parameters. Individual parameters are automatically unwrapped to match primitive formal parameters, and both primitive and reference parameters are subject to method invocation conversions as necessary. If the number of formal parameters required by the underlying constructor is 0, the supplied initargs array may be of length 0 or null. If the constructor’s declaring class is an inner class in a non-static context, the first argument to the constructor needs to be the enclosing instance; see section 15.9.3 of The Java™ Language Specification . If the required access and argument checks succeed and the instantiation will proceed, the constructor’s declaring class is initialized if it has not already been initialized. If the constructor completes normally, returns the newly created and initialized instance.

isVarArgs

Returns true if this executable was declared to take a variable number of arguments; returns false otherwise.

isSynthetic

public boolean isSynthetic()

Источник

Creating New Class Instances

There are two reflective methods for creating instances of classes: java.lang.reflect.Constructor.newInstance() and Class.newInstance() . The former is preferred and is thus used in these examples because:

  • Class.newInstance() can only invoke the zero-argument constructor, while Constructor.newInstance() may invoke any constructor, regardless of the number of parameters.
  • Class.newInstance() throws any exception thrown by the constructor, regardless of whether it is checked or unchecked. Constructor.newInstance() always wraps the thrown exception with an InvocationTargetException .
  • Class.newInstance() requires that the constructor be visible; Constructor.newInstance() may invoke private constructors under certain circumstances.
Читайте также:  Linux cron python script

Sometimes it may be desirable to retrieve internal state from an object which is only set after construction. Consider a scenario where it is necessary to obtain the internal character set used by java.io.Console . (The Console character set is stored in a private field and is not necessarily the same as the Java virtual machine default character set returned by java.nio.charset.Charset.defaultCharset() ). The ConsoleCharset example shows how this might be achieved:

import java.io.Console; import java.nio.charset.Charset; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import static java.lang.System.out; public class ConsoleCharset < public static void main(String. args) < Constructor[] ctors = Console.class.getDeclaredConstructors(); Constructor ctor = null; for (int i = 0; i < ctors.length; i++) < ctor = ctors[i]; if (ctor.getGenericParameterTypes().length == 0) break; >try < ctor.setAccessible(true); Console c = (Console)ctor.newInstance(); Field f = c.getClass().getDeclaredField("cs"); f.setAccessible(true); out.format("Console charset : %s%n", f.get(c)); out.format("Charset.defaultCharset(): %s%n", Charset.defaultCharset()); // production code should handle these exceptions more gracefully >catch (InstantiationException x) < x.printStackTrace(); >catch (InvocationTargetException x) < x.printStackTrace(); >catch (IllegalAccessException x) < x.printStackTrace(); >catch (NoSuchFieldException x) < x.printStackTrace(); >> >

Class.newInstance() will only succeed if the constructor is has zero arguments and is already accessible. Otherwise, it is necessary to use Constructor.newInstance() as in the above example.

Example output for a UNIX system:

$ java ConsoleCharset Console charset : ISO-8859-1 Charset.defaultCharset() : ISO-8859-1

Example output for a Windows system:

C:\> java ConsoleCharset Console charset : IBM437 Charset.defaultCharset() : windows-1252

Another common application of Constructor.newInstance() is to invoke constructors which take arguments. The RestoreAliases example finds a specific single-argument constructor and invokes it:

import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.util.HashMap; import java.util.Map; import java.util.Set; import static java.lang.System.out; class EmailAliases < private Setaliases; private EmailAliases(HashMap h) < aliases = h.keySet(); >public void printKeys() < out.format("Mail keys:%n"); for (String k : aliases) out.format(" %s%n", k); >> public class RestoreAliases < private static MapdefaultAliases = new HashMap(); static < defaultAliases.put("Duke", "duke@i-love-java"); defaultAliases.put("Fang", "fang@evil-jealous-twin"); >public static void main(String. args) < try < Constructor ctor = EmailAliases.class.getDeclaredConstructor(HashMap.class); ctor.setAccessible(true); EmailAliases email = (EmailAliases)ctor.newInstance(defaultAliases); email.printKeys(); // production code should handle these exceptions more gracefully >catch (InstantiationException x) < x.printStackTrace(); >catch (IllegalAccessException x) < x.printStackTrace(); >catch (InvocationTargetException x) < x.printStackTrace(); >catch (NoSuchMethodException x) < x.printStackTrace(); >> >

This example uses Class.getDeclaredConstructor() to find the constructor with a single argument of type java.util.HashMap . Note that it is sufficient to pass HashMap.class since the parameter to any get*Constructor() method requires a class only for type purposes. Due to type erasure, the following expression evaluates to true :

HashMap.class == defaultAliases.getClass()

The example then creates a new instance of the class using this constructor with Constructor.newInstance() .

$ java RestoreAliases Mail keys: Duke Fang

Источник

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