-
Notifications
You must be signed in to change notification settings - Fork 52
io microsphere reflect ConstructorUtils
Type: Class | Module: microsphere-java-core | Package: io.microsphere.reflect | Since: 1.0.0
Source:
microsphere-java-core/src/main/java/io/microsphere/reflect/ConstructorUtils.java
The utilities class of Constructor
public abstract class ConstructorUtils implements UtilsAuthor: Mercy
-
Introduced in:
1.0.0 -
Current Project Version:
0.3.16-SNAPSHOT
This component is tested and compatible with the following Java versions:
| Java Version | Status |
|---|---|
| Java 8 | ✅ Compatible |
| Java 11 | ✅ Compatible |
| Java 17 | ✅ Compatible |
| Java 21 | ✅ Compatible |
| Java 25 | ✅ Compatible |
Constructor<?> constructor = MyClass.class.getConstructor();
boolean isValid = isNonPrivateConstructorWithoutParameters(constructor);boolean result = hasNonPrivateConstructorWithoutParameters(MyClass.class);List<Constructor<?>> constructors = findConstructors(MyClass.class);List<Constructor<?>> nonPrivateConstructors = findConstructors(MyClass.class,
constructor -> !MemberUtils.isPrivate(constructor));List<Constructor<?>> noArgConstructors = findConstructors(MyClass.class,
constructor -> constructor.getParameterCount() == 0);List<Constructor<?>> constructors = findDeclaredConstructors(MyClass.class);List<Constructor<?>> nonPrivateConstructors = findDeclaredConstructors(MyClass.class,
constructor -> !MemberUtils.isPrivate(constructor));List<Constructor<?>> noArgConstructors = findDeclaredConstructors(MyClass.class,
constructor -> constructor.getParameterCount() == 0);Constructor<MyClass> constructor = getConstructor(MyClass.class, String.class, int.class);Constructor<MyClass> constructor = getDeclaredConstructor(MyClass.class, String.class, int.class);Constructor<MyClass> constructor = findConstructor(MyClass.class, String.class, int.class);
if (constructor != null) {
MyClass instance = newInstance(constructor, "example", 42);
}Constructor<MyClass> constructor = findConstructor(MyClass.class, double.class, boolean.class);
if (constructor == null) {
System.out.println("No matching constructor found.");
}Person person = newInstance(Person.class, "Mercy", 18);User user = newInstance(false, User.class, "Alice");Singleton singleton = newInstance(true, Singleton.class);Constructor<MyClass> constructor = MyClass.class.getConstructor(String.class, int.class);
MyClass instance = newInstance(constructor, "hello", 42);Constructor<MyClass> constructor = MyClass.class.getConstructor(String.class);
MyClass instance = newInstance(false, constructor, "hello");Constructor<SingletonClass> constructor = SingletonClass.class.getDeclaredConstructor();
SingletonClass instance = newInstance(true, constructor);Add the following dependency to your pom.xml:
<dependency>
<groupId>io.github.microsphere-projects</groupId>
<artifactId>microsphere-java-core</artifactId>
<version>${microsphere-java.version}</version>
</dependency>Tip: Use the BOM (
microsphere-java-dependencies) for consistent version management. See the Getting Started guide.
import io.microsphere.reflect.ConstructorUtils;| Method | Description |
|---|---|
isNonPrivateConstructorWithoutParameters |
Checks whether the given constructor is a non-private constructor without parameters. |
hasNonPrivateConstructorWithoutParameters |
Checks whether the specified class has at least one non-private constructor without parameters. |
findConstructors |
Find public constructors from the specified class that match the given filter conditions. |
findDeclaredConstructors |
Find declared constructors from the specified class that match the given filter conditions. |
getConstructor |
Retrieves the public constructor of the specified class that matches the given parameter types. |
getDeclaredConstructor |
Retrieves the declared constructor (including private, protected, and package-private) |
findConstructor |
Finds a constructor in the specified class that matches the given parameter types. |
newInstance |
Creates a new instance of the specified class by inferring constructor parameter types |
newInstance |
Creates a new instance of the specified class by locating a declared constructor |
newInstance |
Creates a new instance by invoking the specified Constructor with the provided arguments. |
newInstance |
Creates a new instance by invoking the specified Constructor with optional forced access. |
public static boolean isNonPrivateConstructorWithoutParameters(Constructor<?> constructor)Checks whether the given constructor is a non-private constructor without parameters.
This method verifies that the constructor:
- Is not null
- Is not private (
MemberUtils#isPrivate(Member)) - Has no parameters (i.e., parameter count is less than 1)
`Constructor constructor = MyClass.class.getConstructor(); boolean isValid = isNonPrivateConstructorWithoutParameters(constructor); `
public static boolean hasNonPrivateConstructorWithoutParameters(Class<?> type)Checks whether the specified class has at least one non-private constructor without parameters.
This method examines all declared constructors of the given class and returns true
if any of them is non-private and has no parameters.
`boolean result = hasNonPrivateConstructorWithoutParameters(MyClass.class); `
public static List<Constructor<?>> findConstructors(Class<?> type,
Predicate<? super Constructor<?>>... constructorFilters)Find public constructors from the specified class that match the given filter conditions.
This method retrieves all public constructors of the provided class and filters them based on the specified predicates. It is useful for selecting constructors with specific characteristics, such as visibility, parameter types, or other custom criteria.
`List> constructors = findConstructors(MyClass.class); `
`List> nonPrivateConstructors = findConstructors(MyClass.class,
constructor -> !MemberUtils.isPrivate(constructor));
`
`List> noArgConstructors = findConstructors(MyClass.class,
constructor -> constructor.getParameterCount() == 0);
`
public static List<Constructor<?>> findDeclaredConstructors(Class<?> type,
Predicate<? super Constructor<?>>... constructorFilters)Find declared constructors from the specified class that match the given filter conditions.
This method retrieves all declared constructors (including private, protected, and package-private) of the provided class and filters them based on the specified predicates. It is useful for selecting constructors with specific characteristics such as visibility, parameter types, or other custom criteria.
`List> constructors = findDeclaredConstructors(MyClass.class); `
`List> nonPrivateConstructors = findDeclaredConstructors(MyClass.class,
constructor -> !MemberUtils.isPrivate(constructor));
`
`List> noArgConstructors = findDeclaredConstructors(MyClass.class,
constructor -> constructor.getParameterCount() == 0);
`
public static <T> Constructor<T> getConstructor(Class<T> type, Class<?>... parameterTypes)Retrieves the public constructor of the specified class that matches the given parameter types.
This method attempts to find a public constructor in the provided class that accepts the specified parameter types.
It wraps the underlying reflective operation and handles exceptions via the ThrowableSupplier execution.
`Constructor constructor = getConstructor(MyClass.class, String.class, int.class); `
public static <T> Constructor<T> getDeclaredConstructor(Class<T> type, Class<?>... parameterTypes)Retrieves the declared constructor (including private, protected, and package-private) of the specified class that matches the given parameter types.
This method attempts to find a constructor with the specified parameter types in the provided class.
It wraps the underlying reflective operation and handles exceptions via the ThrowableSupplier execution.
`Constructor constructor = getDeclaredConstructor(MyClass.class, String.class, int.class); `
public static <T> Constructor<T> findConstructor(Class<T> type, Class<?>... parameterTypes)Finds a constructor in the specified class that matches the given parameter types.
This method attempts to locate a constructor within the provided class that accepts the specified parameter types.
If no such constructor is found, it returns null and logs a trace message indicating the failure.
`Constructor constructor = findConstructor(MyClass.class, String.class, int.class);
if (constructor != null) {
MyClass instance = newInstance(constructor, "example", 42);
`
}
`Constructor constructor = findConstructor(MyClass.class, double.class, boolean.class);
if (constructor == null) {
System.out.println("No matching constructor found.");
`
}
public static <T> T newInstance(Class<T> type, Object... args)Creates a new instance of the specified class by inferring constructor parameter types
from the runtime types of args.
This method delegates to #newInstance(boolean, Class, Object...) with
forceAccess = false, so normal Java access checks apply.
`Person person = newInstance(Person.class, "Mercy", 18); `
public static <T> T newInstance(boolean forceAccess, Class<T> type, Object... args)Creates a new instance of the specified class by locating a declared constructor that matches the runtime argument types and invoking it.
When forceAccess is true, this method attempts to make the resolved
constructor accessible before invocation, which allows use of non-public constructors.
`User user = newInstance(false, User.class, "Alice"); `
`Singleton singleton = newInstance(true, Singleton.class); `
public static <T> T newInstance(Constructor<T> constructor, Object... args)Creates a new instance by invoking the specified Constructor with the provided arguments.
This method uses normal Java access checks and delegates to
#newInstance(boolean, Constructor, Object...) with forceAccess = false.
`Constructor constructor = MyClass.class.getConstructor(String.class, int.class); MyClass instance = newInstance(constructor, "hello", 42); `
public static <T> T newInstance(boolean forceAccess, Constructor<T> constructor, Object... args)Creates a new instance by invoking the specified Constructor with optional forced access.
When forceAccess is true, this method attempts to make the constructor accessible first,
allowing invocation of non-public constructors. When forceAccess is false, normal Java
access checks apply.
`Constructor constructor = MyClass.class.getConstructor(String.class); MyClass instance = newInstance(false, constructor, "hello"); `
`Constructor constructor = SingletonClass.class.getDeclaredConstructor(); SingletonClass instance = newInstance(true, constructor); `
This documentation was auto-generated from the source code of microsphere-java.
annotation-processor
- ConfigurationPropertyAnnotationProcessor
- ConfigurationPropertyJSONElementVisitor
- FilerProcessor
- ResourceProcessor
annotation-test
java-annotations
java-core
- ACLLoggerFactory
- AbstractArtifactResourceResolver
- AbstractConverter
- AbstractDeque
- AbstractEventDispatcher
- AbstractLogger
- AbstractSerializer
- AbstractURLClassPathHandle
- AccessibleObjectUtils
- AdditionalMetadataResourceConfigurationPropertyLoader
- AnnotationUtils
- ArchiveFileArtifactResourceResolver
- ArrayEnumeration
- ArrayStack
- ArrayUtils
- Artifact
- ArtifactDetector
- ArtifactResourceResolver
- Assert
- BannedArtifactClassLoadingExecutor
- BaseUtils
- BeanMetadata
- BeanProperty
- BeanUtils
- BooleanSerializer
- ByteArrayToObjectConverter
- ByteSerializer
- CharSequenceComparator
- CharSequenceUtils
- CharacterSerializer
- CharsetUtils
- ClassDataRepository
- ClassDefinition
- ClassFileJarEntryFilter
- ClassFilter
- ClassLoaderUtils
- ClassPathResourceConfigurationPropertyLoader
- ClassPathUtils
- ClassUtils
- ClassicProcessIdResolver
- ClassicURLClassPathHandle
- CollectionUtils
- Compatible
- CompositeSubProtocolURLConnectionFactory
- CompositeURLStreamHandlerFactory
- ConditionalEventListener
- ConfigurationProperty
- ConfigurationPropertyGenerator
- ConfigurationPropertyLoader
- ConfigurationPropertyReader
- Configurer
- ConsoleURLConnection
- ConstantPoolUtils
- Constants
- ConstructorDefinition
- ConstructorUtils
- Converter
- Converters
- CustomizedThreadFactory
- DefaultConfigurationPropertyGenerator
- DefaultConfigurationPropertyReader
- DefaultDeserializer
- DefaultEntry
- DefaultSerializer
- DelegatingBlockingQueue
- DelegatingDeque
- DelegatingIterator
- DelegatingQueue
- DelegatingScheduledExecutorService
- DelegatingURLConnection
- DelegatingURLStreamHandlerFactory
- DelegatingWrapper
- Deprecation
- Deserializer
- Deserializers
- DirectEventDispatcher
- DirectoryFileFilter
- DoubleSerializer
- EmptyDeque
- EmptyIterable
- EmptyIterator
- EnumSerializer
- EnumerationIteratorAdapter
- EnumerationUtils
- Event
- EventDispatcher
- EventListener
- ExceptionUtils
- ExecutableDefinition
- ExecutableUtils
- ExecutorUtils
- ExtendableProtocolURLStreamHandler
- FastByteArrayInputStream
- FastByteArrayOutputStream
- FieldDefinition
- FieldUtils
- FileChangedEvent
- FileChangedListener
- FileConstants
- FileExtensionFilter
- FileUtils
- FileWatchService
- Filter
- FilterOperator
- FilterUtils
- FloatSerializer
- FormatUtils
- Functional
- GenericEvent
- GenericEventListener
- Handler
- Handler
- HierarchicalClassComparator
- IOFileFilter
- IOUtils
- ImmutableEntry
- IntegerSerializer
- IterableAdapter
- IterableUtils
- Iterators
- JDKLoggerFactory
- JSON
- JSONArray
- JSONException
- JSONObject
- JSONStringer
- JSONTokener
- JSONUtils
- JarEntryFilter
- JarUtils
- JavaType
- JmxUtils
- LambdaUtils
- ListUtils
- Listenable
- Lists
- Logger
- LoggerFactory
- LoggingFileChangedListener
- LongSerializer
- MBeanAttribute
- MBeanAttributeInfoBuilder
- MBeanConstructorInfoBuilder
- MBeanDescribableBuilder
- MBeanExecutableInfoBuilder
- MBeanFeatureInfoBuilder
- MBeanInfoBuilder
- MBeanNotificationInfoBuilder
- MBeanOperationInfoBuilder
- MBeanParameterInfoBuilder
- ManagementUtils
- ManifestArtifactResourceResolver
- MapToPropertiesConverter
- MapUtils
- Maps
- MavenArtifact
- MavenArtifactResourceResolver
- MemberDefinition
- MemberUtils
- MetadataResourceConfigurationPropertyLoader
- MethodDefinition
- MethodHandleUtils
- MethodHandlesLookupUtils
- MethodUtils
- ModernProcessIdResolver
- ModernURLClassPathHandle
- Modifier
- MultiValueConverter
- MultipleType
- MutableInteger
- MutableURLStreamHandlerFactory
- NameFileFilter
- NoOpLogger
- NoOpLoggerFactory
- NoOpURLClassPathHandle
- NumberToByteConverter
- NumberToCharacterConverter
- NumberToDoubleConverter
- NumberToFloatConverter
- NumberToIntegerConverter
- NumberToLongConverter
- NumberToShortConverter
- NumberUtils
- ObjectToBooleanConverter
- ObjectToByteArrayConverter
- ObjectToByteConverter
- ObjectToCharacterConverter
- ObjectToDoubleConverter
- ObjectToFloatConverter
- ObjectToIntegerConverter
- ObjectToLongConverter
- ObjectToOptionalConverter
- ObjectToShortConverter
- ObjectToStringConverter
- ObjectUtils
- PackageNameClassFilter
- PackageNameClassNameFilter
- ParallelEventDispatcher
- ParameterizedTypeImpl
- PathConstants
- Predicates
- Prioritized
- PriorityComparator
- ProcessExecutor
- ProcessIdResolver
- ProcessManager
- PropertiesToStringConverter
- PropertiesUtils
- PropertyConstants
- PropertyResourceBundleControl
- PropertyResourceBundleUtils
- ProtocolConstants
- ProxyUtils
- QueueUtils
- ReadOnlyIterator
- ReflectionUtils
- ReflectiveConfigurationPropertyGenerator
- ReflectiveDefinition
- ResourceConstants
- ReversedDeque
- Scanner
- SecurityUtils
- SeparatorConstants
- Serializer
- Serializers
- ServiceLoaderURLStreamHandlerFactory
- ServiceLoaderUtils
- ServiceLoadingURLClassPathHandle
- SetUtils
- Sets
- Sfl4jLoggerFactory
- ShortSerializer
- ShutdownHookCallbacksThread
- ShutdownHookUtils
- SimpleClassScanner
- SimpleFileScanner
- SimpleJarEntryScanner
- SingletonDeque
- SingletonEnumeration
- SingletonIterator
- SizeUtils
- StackTraceUtils
- StandardFileWatchService
- StandardURLStreamHandlerFactory
- StopWatch
- StreamArtifactResourceResolver
- Streams
- StringBuilderWriter
- StringConverter
- StringDeserializer
- StringSerializer
- StringToArrayConverter
- StringToBlockingDequeConverter
- StringToBlockingQueueConverter
- StringToBooleanConverter
- StringToByteConverter
- StringToCharArrayConverter
- StringToCharacterConverter
- StringToClassConverter
- StringToCollectionConverter
- StringToDequeConverter
- StringToDoubleConverter
- StringToDurationConverter
- StringToFloatConverter
- StringToInputStreamConverter
- StringToIntegerConverter
- StringToIterableConverter
- StringToListConverter
- StringToLongConverter
- StringToMultiValueConverter
- StringToNavigableSetConverter
- StringToQueueConverter
- StringToSetConverter
- StringToShortConverter
- StringToSortedSetConverter
- StringToStringConverter
- StringToTransferQueueConverter
- StringUtils
- SubProtocolURLConnectionFactory
- SymbolConstants
- SystemUtils
- ThrowableAction
- ThrowableBiConsumer
- ThrowableBiFunction
- ThrowableConsumer
- ThrowableFunction
- ThrowableSupplier
- ThrowableUtils
- TrueClassFilter
- TrueFileFilter
- TypeArgument
- TypeFinder
- TypeUtils
- URLClassPathHandle
- URLUtils
- UnmodifiableDeque
- UnmodifiableIterator
- UnmodifiableQueue
- UnsafeUtils
- Utils
- ValueHolder
- Version
- VersionUtils
- VirtualMachineProcessIdResolver
- Wrapper
- WrapperProcessor
java-test
- Ancestor
- ArrayTypeModel
- CollectionTypeModel
- Color
- ConfigurationPropertyModel
- DefaultTestService
- GenericTestService
- MapTypeModel
- Model
- Parent
- PrimitiveTypeModel
- SimpleTypeModel
- StringArrayList
- TestAnnotation
- TestService
- TestServiceImpl
jdk-tools
lang-model