我想能够说出一个此类的实例并提供一个类型,然后代码可以实例化该类的新实例。
fun maker(type: Class<Animal>): Animal {
if(type == Class<Dog>) {
return Dog()
}
else if (type == Class<Cat>) {}
...
}
执行此操作的好方法是什么?
答案 0 :(得分:2)
如果它们都具有零参数构造函数,则可以执行以下操作:
SettingWithCopyWarning
您可以使其返回传入的类型,以实现更多用途:
fun maker(type: Class<Animal>): Animal {
return type.newInstance()
}
答案 1 :(得分:1)
遵循您的示例的正确版本(不确定总体上最佳方法):
import numpy as np
# oddly enough - numpy doesn't have it's own ffill function:
def np_ffill(arr):
mask = np.arange(len(arr))
mask[np.isnan(arr)]=0
np.maximum.accumulate(mask, axis=0, out=mask)
return arr[mask]
t1=np.ceil(t1).astype("int")
t2=np.ceil(t2).astype("int")
r1=np.empty(max(t1)+1)
r2=np.empty(max(t2)+1)
r1[:]=np.nan
r2[:]=np.nan
r1[t1]=m1
r2[t2]=m2
r1=np_ffill(r1)
r2=np_ffill(r2)
>>> print(r1,r2)
[0.4 0.4 0.4 0.6 0.6 0.6 0.2] [1. 1. 1. 1. 1.4 1. ]
#in order to get avg:
r3=np.vstack([r1[:len(r2)],r2[:len(r1)]]).mean(axis=0)
>>> print(r3)
[0.7 0.7 0.7 0.8 1. 0.8]
然后创建对象:
fun <T: Animal> maker(type: Class<T>): T? {
return when (type) {
Cat::class.java -> Cat() as T
Dog::class.java -> Dog() as T
else -> null
}
}
答案 2 :(得分:0)
(已更新)我不是Kotlin专家,但是您可以执行以下操作:
import kotlin.reflect.KClass
import kotlin.reflect.full.createInstance
class A {
fun greet() {
println("Hello A");
}
}
class B{
fun greet() {
println("Hello B");
}
}
fun <T : Any> maker(clazz: KClass<T>): T {
return clazz.createInstance();
}
val aObj = maker<A>(A::class);
aObj.greet();
val bObj = maker<B>(B::class);
bObj.greet();
输出:
Hello A
Hello B
我希望现在您只需要将类传递给方法并返回一个对象就可以了。
因为您将使用Animal作为父类,所以可以替换Any => Animal
fun <T : Animal> maker(clazz: KClass<T>): T {
return clazz.createInstance();
}
答案 3 :(得分:0)
如果函数可以为import com.ghgande.j2mod.modbus.facade.ModbusSerialMaster;
import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.ModbusException;
import com.ghgande.j2mod.modbus.procimg.Register;
import com.ghgande.j2mod.modbus.util.SerialParameters;
public class ModbusMaster
{
/**
* @param args
*/
public static void main(String[] args)
{
/* The important instances of the classes mentioned before */
ModbusSerialMaster serialMaster = null; // the connection
/* Variables for storying the parameters */
String portname = "COM3"; // the name of the serial port to be used
int unitID = 1 ; // the unit identifier we will be talking to
int startingRegister = 10001; // the reference, where to start reading from
int registerCount = 0; // the count of the input registers to read
Register[] slaveResponse = new Register[registerCount];
try
{
/* Setup the serial parameters */
SerialParameters parameters = new SerialParameters();
parameters.setPortName(portname);
parameters.setBaudRate(9600);
parameters.setDatabits(8);
parameters.setParity("None");
parameters.setStopbits(1);
parameters.setEncoding(Modbus.SERIAL_ENCODING_RTU);
parameters.setEcho(false);
/* Open the connection */
serialMaster = new ModbusSerialMaster(parameters);
serialMaster.connect();
}
catch (Exception exception)
{
System.out.println("Not Run");
exception.printStackTrace();
}
/* Read the first four holding registers */
try
{
slaveResponse = serialMaster.readMultipleRegisters(unitID, startingRegister, registerCount);
for (int i = 0; i < slaveResponse.length; i++)
{
System.out.println("reg" + i + " = " + slaveResponse[i]);
}
}
catch (ModbusException e)
{
e.printStackTrace();
}
/* Close the connection */
serialMaster.disconnect();
}
}
,则也可以使用reified类型
com.ghgande.j2mod.modbus.ModbusIOException: I/O exception - failed to read
at com.ghgande.j2mod.modbus.io.ModbusRTUTransport.readResponse(ModbusRTUTransport.java:645)
at com.ghgande.j2mod.modbus.io.ModbusSerialTransaction.execute(ModbusSerialTransaction.java:189)
at com.ghgande.j2mod.modbus.facade.ModbusSerialMaster.readMultipleRegisters(ModbusSerialMaster.java:269)
at ModbusMaster.main(ModbusMaster.java:53)
请注意,要使用inline
,该类必须具有no-arg构造函数,否则将抛出inline fun<reified T: Animal> make() = T::class.createInstance()
...
val dog = make<Dog>()