简体   繁体   中英

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?

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.

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, ie 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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