开发者

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

开发者 https://www.devze.com 2023-03-17 18:18 出处:网络
How do you pass a class type as parameter? public Configuration getConfig(Object mapper, Object format) {

How do you pass a class type as parameter?

public Configuration getConfig(Object mapper, Object format) {
    Configura开发者_如何学运维tion 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.

I'm not sure how to convert from Object to TestMapper.class.


The parameters to getConfig() should perhaps have Class type in in the first place instead of Object's. However:

If you want the runtime class of whatever your mapper and format Objects are, just call their .getClass() methods.

 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.

If your mapper and parameter already is the .class objects, i.e. you have called the method as foo.getConfig(TestMapper.class,DatastoreInputFormat.class); you can cast your Objects back to a Class object, assuming the conf.setClass() takes Class<?> type:

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(). If it is Configuration.setClass(String, Class, Class) you can convert from Object to Class by casting: (Class)mapper and (Class)format`.

Although it is a bad style as all casting... Why getConfig() receives Objects? May be it should receive arguments of type Class? In this case you even do not need any casting at all.

0

精彩评论

暂无评论...
验证码 换一张
取 消