org.jboss.marshalling.ChainingClassExternalizerFactory Maven / Gradle / Ivy
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.marshalling;
import java.util.Collection;
import java.util.Iterator;
/**
* A class externalizer factory that tries each delegate externalizer factory in sequence, returning the first match.
*/
public class ChainingClassExternalizerFactory implements ClassExternalizerFactory {
private final ClassExternalizerFactory[] externalizerFactories;
/**
* Construct a new instance.
*
* @param factories a collection of factories to use
*/
public ChainingClassExternalizerFactory(final Collection factories) {
externalizerFactories = factories.toArray(new ClassExternalizerFactory[factories.size()]);
}
/**
* Construct a new instance.
*
* @param factories a collection of factories to use
*/
public ChainingClassExternalizerFactory(final Iterable factories) {
this(factories.iterator());
}
/**
* Construct a new instance.
*
* @param factories a sequence of factories to use
*/
public ChainingClassExternalizerFactory(final Iterator factories) {
externalizerFactories = unroll(factories, 0);
}
/**
* Construct a new instance.
*
* @param factories an array of factories to use
*/
public ChainingClassExternalizerFactory(final ClassExternalizerFactory[] factories) {
externalizerFactories = factories.clone();
}
private static ClassExternalizerFactory[] unroll(final Iterator iterator, final int i) {
if (iterator.hasNext()) {
final ClassExternalizerFactory factory = iterator.next();
final ClassExternalizerFactory[] array = unroll(iterator, i + 1);
array[i] = factory;
return array;
} else {
return new ClassExternalizerFactory[i];
}
}
/** {@inheritDoc} This implementation tries each nested externalizer factory in order until a match is found. */
public Externalizer getExternalizer(final Class> type) {
for (ClassExternalizerFactory externalizerFactory : externalizerFactories) {
final Externalizer externalizer = externalizerFactory.getExternalizer(type);
if (externalizer != null) {
return externalizer;
}
}
return null;
}
}