读书人

Lucene之AttributeImpl源码简略

发布时间: 2013-07-08 14:13:00 作者: rapoo

Lucene之AttributeImpl源码简单
public abstract class AttributeImpl implements Cloneable, Attribute {/* * 抽象有两个方法一个clean方法一个copyTo方法 但是copy方法返回是一个void?说明修改后直接改变的还是对象内容。 */public abstract void clear();public abstract void copyTo(AttributeImpl target);/* * 这个方法好奇怪,下面的方法调用居然根据这个变量来处理 */public final String reflectAsString(final boolean prependAttClass) {/* *   *StringBuild 没线程安全 效率更高   *StringBuffer 线程安全   * */final StringBuilder buffer = new StringBuilder();/* * AttributeReflector是一个接口里面只有一个方法。   * * AttributeReflector(接口,字段属性《剔除静态的》,值); */reflectWith(new AttributeReflector() {@Overridepublic void reflect(Class<? extends Attribute> attClass,String key, Object value) {if (buffer.length() > 0) {buffer.append(',');}/* * 如果是false的话类名不用添加了 */if (prependAttClass) {buffer.append(attClass.getName()).append('#');}/* * buffer添加字符串key=对于value为空null否则就添加value */buffer.append(key).append('=').append((value == null) ? "null" : value);}});return buffer.toString();}public void reflectWith(AttributeReflector reflector) {// 得到Class也就是反射了final Class<? extends AttributeImpl> clazz = this.getClass();// 通过AttributeSource得到 从字面意思是得到所有的接口final LinkedList<WeakReference<Class<? extends Attribute>>> interfaces = AttributeSource.getAttributeInterfaces(clazz);// 如果没接口抛出异常if (interfaces.size() != 1) {throw new UnsupportedOperationException(clazz.getName()+ " implements more than one Attribute interface, the default reflectWith() implementation cannot handle this.");}// 下面应该是得到第一个接口?但是是为什么那?只得到第一个哪?final Class<? extends Attribute> interf = interfaces.getFirst().get();final Field[] fields = clazz.getDeclaredFields();try {for (int i = 0; i < fields.length; i++) {final Field f = fields[i];// 得到所有的属性,但是静态属性就去掉了if (Modifier.isStatic(f.getModifiers()))continue;f.setAccessible(true);reflector.reflect(interf, f.getName(), f.get(this));}} catch (IllegalAccessException e) {// this should never happen, because we're just accessing fields// from 'this'throw new RuntimeException(e);}}/* * 返回一个克隆的对象 */@Overridepublic AttributeImpl clone() {AttributeImpl clone = null;try {clone = (AttributeImpl) super.clone();} catch (CloneNotSupportedException e) {throw new RuntimeException(e); // shouldn't happen}return clone;}}

?

读书人网 >开源软件

热点推荐