简体   繁体   English

如何将泛型类型('Object myVar')作为参数传递来替换 class 类型('SomeClass.class')?

[英]How do you pass a generic type ('Object myVar') as a parameter to replace a class type ('SomeClass.class')?

How do you pass a class type as parameter?如何将 class 类型作为参数传递?

public Configuration getConfig(Object mapper, Object format) {
    Configuration conf = new Configuration(false);
    conf.setClass("mapreduce.map.class", TestMapper.class, Mapper.class);
    conf.setClass("mapreduce.inputformat.class", DatastoreInputFormat.class, InputFormat.class);
    return conf;
}

I want to replace the value TestMapper.class and DatastoreInputFormat.class with the parameters mapper and format , respectively.我想分别用参数mapperformat替换值TestMapper.classDatastoreInputFormat.class

I'm not sure how to convert from Object to TestMapper.class .我不确定如何从Object转换为TestMapper.class

The parameters to getConfig() should perhaps have Class type in in the first place instead of Object's. getConfig() 的参数应该首先输入 Class 类型而不是 Object 类型。 However:然而:

If you want the runtime class of whatever your mapper and format Objects are, just call their.getClass() methods.如果你想要运行时 class 无论你的映射器和格式对象是什么,只需调用 their.getClass() 方法。

 conf.setClass("mapreduce.map.class",mapper.getClass(), Mapper.class);
 conf.setClass("mapreduce.inputformat.class",format.getClass(),InputFormat.class);

So, if your mapper method parameter is actually an instance of TestMapper, mapper.getClass() will return the same object as TestMapper.class does.因此,如果您的mapper方法参数实际上是 TestMapper 的一个实例,则 mapper.getClass() 将返回与 TestMapper.class 相同的 object。

If your mapper and parameter already is the.class objects, ie you have called the method as foo.getConfig(TestMapper.class,DatastoreInputFormat.class);如果您的mapperparameter已经是 .class 对象,即您已将该方法称为foo.getConfig(TestMapper.class,DatastoreInputFormat.class); you can cast your Objects back to a Class object, assuming the conf.setClass() takes Class<?> type:您可以将您的对象转换回 Class object,假设 conf.setClass() 采用Class<?>类型:

conf.setClass("mapreduce.map.class",(Class<?>)mapper, Mapper.class);
conf.setClass("mapreduce.inputformat.class",(Class<?>)format,InputFormat.class);

Unfortunately it is not clear what is the prototype of Configuration.setClass() .不幸的是,尚不清楚Configuration.setClass()的原型是什么。 If it is Configuration.setClass(String, Class, Class) you can convert from Object to Class by casting: (Class)mapper and (Class)format`.如果它是Configuration.setClass(String, Class, Class)你可以从 Object 转换为 Class 通过转换: (Class)mapper和 (Class)format`。

Although it is a bad style as all casting... Why getConfig() receives Objects?虽然它是一种糟糕的风格,因为所有的铸造......为什么 getConfig() 接收对象? May be it should receive arguments of type Class?可能应该收到 Class 类型的 arguments 吗? In this case you even do not need any casting at all.在这种情况下,您甚至根本不需要任何铸造。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM