Lucene之AttributeImpl源码简单

一、简单介绍

Attribute接口是一个空接口;

AttributeImpl也继承Attribute接口;

                        根据源码是:记录对象的属性,但是不包含静态属性

                        对于一些属性是Attribute是接口,然后AttributeImpl去实现接口。

                        例如:OffsetAttribute 和 OffsetAttributeImpl

二、简单源码分析

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() {
			@Override
			public 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);
		}
	}

	/*
	 * 返回一个克隆的对象
	 */
	@Override
	public AttributeImpl clone() {
		AttributeImpl clone = null;
		try {
			clone = (AttributeImpl) super.clone();
		} catch (CloneNotSupportedException e) {
			throw new RuntimeException(e); // shouldn't happen
		}
		return clone;
	}
}

 

猜你喜欢

转载自xiaozhou09.iteye.com/blog/1887544
今日推荐