简体   繁体   English

Java - 使用Reflection创建新实例,而不需要知道构造函数参数

[英]Java - Create new Instance using Reflection without knowing constructor params

I need to create new instances of many classes. 我需要创建许多类的新实例。 I'm using reflection but when I make c.newInstance(), the classes without 'empty parameter constructor' throws an java.lang.InstantiationException. 我正在使用反射但是当我创建c.newInstance()时,没有'empty parameter constructor'的类会抛出java.lang.InstantiationException。

Now, how can i do to create instances of every classes ? 现在,我该怎么做才能创建每个类的实例?

I know that i can use c.getConstructor(Class).newinstance(params) to create instances of classes that doesn't have 'empty parameter constructor', but i do not know the params of each classes. 我知道我可以使用c.getConstructor(Class).newinstance(params)创建没有'空参数构造函数'的类的实例,但我不知道每个类的参数。

One more thing, all those classes extend from another class called ParentClass, so one workaround that i could use is to include some code in the ParentClass that force the child classes to implement an 'empty parameter constructor', but don't know how to do this. 还有一件事,所有这些类都扩展自另一个名为ParentClass的类,因此我可以使用的一种解决方法是在ParentClass中包含一些强制子类实现“空参数构造函数”的代码,但不知道如何做这个。

Thanks in advance ! 提前致谢 !

You can call Class.getConstructors() to get all the constructors for a given class. 您可以调用Class.getConstructors()来获取给定类的所有构造函数。

On each Constructor , you can call Constructor.getGenericParameterTypes() to learn which parameters it expects. 在每个构造函数上 ,您可以调用Constructor.getGenericParameterTypes()来了解它所期望的参数。

You can't. 你不能。 There's no way to "require" a parameterless constructor and have it enforced by the compiler, and by definition to create an instance of a class you must provide it with the necessary parameters, or otherwise you'll wind up with an object that violates the class contract (because it is not initialized properly). 没有办法“需要”无参数构造函数并由编译器强制执行,并且根据定义创建类的实例,您必须为其提供必要的参数,否则您最终会得到一个违反该参数的对象。 class contract(因为它没有正确初始化)。

The proper way to enforce this at a code level is with an object factory and interfaces. 在代码级别强制执行此操作的正确方法是使用对象工厂和接口。 I'm presuming that you're having to use reflection because you don't know about the types at compile time; 我假设您必须使用反射,因为您在编译时不了解类型; In this case, there should also be a "Factory" which knows how to produce instances of each type. 在这种情况下,还应该有一个“工厂”知道如何生成每种类型的实例。 This factory should be built/compiled with the type in question, so that it is aware of and can invoke the proper constructor. 应该使用有问题的类型构建/编译此工厂,以便它知道并可以调用正确的构造函数。 The Factory then implements an interface which your code is aware of, such as "ObjectFactory", that allows you to delegate to the factory for instantiating objects. 然后,Factory会实现一个代码可以识别的接口,例如“ObjectFactory”,它允许您委托工厂实例化对象。 You would then have some method which an object factory can use to register as being responsible for whatever types it can instantiate. 然后,您将拥有一些对象工厂可以用来注册的方法,以便对它可以实例化的任何类型负责。

In the code that ships with the classes you're trying to create: 在您尝试创建的类附带的代码中:

static {
    FactoryRegistry.register(TypeA.class, new TypeAFactory());
}

And in your code: 在你的代码中:

Class<?> unknownClass = ...;
Object obj = FactoryRegistry.getFactory(unknownClass).newInstance();

(where you have a Factory interface that TypeAFactory implements and specifies the newInstance method) (您有一个TypeAFactory实现的Factory接口并指定newInstance方法)

You don't know what unknownClass is or how to instantiate it, but if the code that came with that class registered a factory, you can query for that factory and ask it to create the object for you. 您不知道unknownClass是什么或如何实例化它,但如果该类附带的代码注册了工厂,您可以查询该工厂并​​要求它为您创建对象。 If unknownClass is really TypeA.class , then the registry will return the TypeAFactory that was registered to create objects. 如果unknownClass确实是TypeA.class ,那么注册表将返回已注册以创建对象的TypeAFactory


Alternatively, you can just require that the authors of any code your framework is loading dynamically include an argument-less constructor. 或者,您可以要求您的框架动态加载的任何代码的作者都包含无参数构造函数。 It's not rigidly enforced, but can be easier for authors to implement. 它没有严格执行,但作者可以更容易实现。

There are two reflective methods for creating instances of classes : java.lang.reflect.Constructor.newInstance() and Class.newInstance() 创建类的实例两种反射方法java.lang.reflect.Constructor.newInstance()Class.newInstance()

Class.newInstance() can only invoke the zero-argument constructor , while Class.newInstance()只能调用零参数构造函数

Constructor.newInstance() may invoke any constructor, regardless of the number of parameters . 无论参数的数量如何,Constructor.newInstance()都可以调用任何构造函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Java 反射:使用树形图中的参数创建实例,如 python - Java reflection: create a instance using params from a treemap like python 如何使用零参数构造函数创建具有通过Java反射绑定的上下文的Scala类的新实例? - How to create new instance of Scala class with context bound via Java reflection using only zero argument constructor? 是否有可能在java中使用反射创建没有arg构造函数的类的“空白”实例? - Is it possible in java to create 'blank' instance of class without no-arg constructor using reflection? 从Java反射创建对象而无需了解构造函数参数 - Creating a object from java reflection without knowing the constructor parameters Java反射创建未知类和构造函数的实例 - Java reflection create instance of unknown class and constructor Java 8:使用反射使用泛型创建类的新实例 - Java 8: create new instance of class with generics using reflection 使用Java中的反射创建一个新实例,并将引用变量类型设置为新的实例类名称? - Using reflection in Java to create a new instance with the reference variable type set to the new instance class name? 使用Java Reflection API转换枚举而不知道类型 - Convert Enums without knowing the type using Java Reflection API 如何在Java中使用反射创建枚举实例? - How to create an instance of enum using reflection in Java? 反射:创建实例-java - Reflection: create an instance -java
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM