hadoop1.0.4
有时在编写Hadoop的MR的时候,会想到如果在Configuration里面可以设置一个类变量多好呀。查看Configuration的api可以看到,一般set方法都是set一般数据类型,比如int,string或者double之类的。那有没有一个方法设置一个自定义类的变量呢,比如setClass,还真别说,还真有这个方法。
查看api:
setClass
public void setClass(String name,
Class<?> theClass,
Class<?> xface)
Set the value of the name property to the name of a theClass implementing the given interface xface. An exception is thrown if theClass does not implement the interface xface.
Parameters:
name - property name.
theClass - property value.
xface - the interface implemented by the named class.
但是,感觉不怎么对的?网上查了下,发现这个是设置类型的,用法如下:
/**
* 根据变量获得数据类型
*/
public static void testSetClass(){
Configuration conf= new Configuration();
conf.setClass("mapout", LongWritable.class , Writable.class);
Class<?> b=conf.getClass("mapout", Writable.class);
System.out.println(b);
conf.setClass("myClass", User.class, Person.class);
b=conf.getClass("myClass", Person.class);
System.out.println(b);
}
这样打印出来的是(User是Person的子类):
class org.apache.hadoop.io.LongWritable
class org.fz.testconfig.User
这个其实就是设置类型用的,感觉用处不是很大。如果想在Mapper或者Reducer的setup函数中获得某个类型,那么其实也可以使用下面的方式:
/**
* 根据包路径获得数据类型
* @throws ClassNotFoundException
*/
public static void testGetClassByName() throws ClassNotFoundException{
Configuration conf= new Configuration();
Class<?> a=conf.getClassByName("org.apache.hadoop.io.Long