/** * Adapts the source object to a view object. * * @param mapper An action that is invoked for each source object in the graph that is to be * adapted. The action can influence how the source object is adapted via the provided {@link * SourceObjectMapping}. */ public <T, S> T adapt( Class<T> targetType, S sourceObject, Action<? super SourceObjectMapping> mapper) { if (sourceObject == null) { return null; } Class<? extends T> wrapperType = targetTypeProvider.getTargetType(targetType, sourceObject); DefaultSourceObjectMapping mapping = new DefaultSourceObjectMapping(sourceObject, targetType, wrapperType); mapper.execute(mapping); wrapperType = mapping.wrapperType.asSubclass(targetType); if (wrapperType.isInstance(sourceObject)) { return wrapperType.cast(sourceObject); } if (targetType.isEnum()) { return adaptToEnum(targetType, sourceObject); } MixInMethodInvoker mixInMethodInvoker = null; if (mapping.mixInType != null) { mixInMethodInvoker = new MixInMethodInvoker( mapping.mixInType, new AdaptingMethodInvoker(mapper, new ReflectionMethodInvoker())); } MethodInvoker overrideInvoker = chainInvokers(mixInMethodInvoker, mapping.overrideInvoker); Object proxy = Proxy.newProxyInstance( wrapperType.getClassLoader(), new Class<?>[] {wrapperType}, new InvocationHandlerImpl(sourceObject, overrideInvoker, mapper)); if (mixInMethodInvoker != null) { mixInMethodInvoker.setProxy(proxy); } return wrapperType.cast(proxy); }
private static <T> T getParamXPath( final Class<T> pClass, final String pXpath, final CompactFragment pBody) throws XmlException { // TODO Avoid JAXB where possible, use XMLDeserializer instead final boolean string = CharSequence.class.isAssignableFrom(pClass); Node match; DocumentFragment fragment = DomUtil.childrenToDocumentFragment(XMLFragmentStreamReader.from(pBody)); for (Node n = fragment.getFirstChild(); n != null; n = n.getNextSibling()) { match = xpathMatch(n, pXpath); if (match != null) { if (!string) { XmlDeserializer deserializer = pClass.getAnnotation(XmlDeserializer.class); if (deserializer != null) { try { XmlDeserializerFactory<?> factory = deserializer.value().newInstance(); factory.deserialize(XmlStreaming.newReader(new DOMSource(n))); } catch (InstantiationException | IllegalAccessException e) { throw new RuntimeException(e); } } else { return JAXB.unmarshal(new DOMSource(match), pClass); } } else { return pClass.cast(nodeToString(match)); } } } return null; }
@Deprecated public <T extends Widget> T findchild(Class<T> cl) { for (Widget wdg = child; wdg != null; wdg = wdg.next) { if (cl.isInstance(wdg)) return (cl.cast(wdg)); T ret = wdg.findchild(cl); if (ret != null) return (ret); } return (null); }
public <T> T getInterface(Object thiz, Class<T> iface) throws ScriptException { if (iface == null || !iface.isInterface()) { throw new IllegalArgumentException("interface Class expected"); } AccessControlContext accCtxt = AccessController.getContext(); return iface.cast( Proxy.newProxyInstance( iface.getClassLoader(), new Class[] {iface}, new InterfaceImplementorInvocationHandler(thiz, accCtxt))); }
public <T> T nodeByTypeElement(Class<T> baseType) { int len = children.size(); for (int i = 0; i < len; i++) { Child child = children.get(i); if (child instanceof NodeChild) { NodeChild nc = (NodeChild) child; if (model.elements.containsKey(nc.name)) continue; // match with named if (baseType.isAssignableFrom(nc.dom.getImplementationClass())) return baseType.cast(nc.dom.get()); } } return null; }
private static <T, S> T adaptToEnum(Class<T> targetType, S sourceObject) { try { String literal; if (sourceObject instanceof Enum) { literal = ((Enum<?>) sourceObject).name(); } else if (sourceObject instanceof String) { literal = (String) sourceObject; } else { literal = sourceObject.toString(); } NotationParser<String, T> parser = new NotationConverterToNotationParserAdapter<String, T>( new EnumFromCharSequenceNotationParser(targetType)); T parsedLiteral = parser.parseNotation(literal); return targetType.cast(parsedLiteral); } catch (TypeConversionException e) { throw new IllegalArgumentException( String.format( "Can't convert '%s' to enum type '%s'", sourceObject, targetType.getSimpleName()), e); } }
// Other notes to implementors: // <p> // No stable mapping is promised between the single-method interface and // the implementation class C. Over time, several implementation // classes might be used for the same type. // <p> // If the implementation is able // to prove that a wrapper of the required type // has already been created for a given // method handle, or for another method handle with the // same behavior, the implementation may return that wrapper in place of // a new wrapper. // <p> // This method is designed to apply to common use cases // where a single method handle must interoperate with // an interface that implements a function-like // API. Additional variations, such as single-abstract-method classes with // private constructors, or interfaces with multiple but related // entry points, must be covered by hand-written or automatically // generated adapter classes. // public static <T> T asInterfaceInstance(final Class<T> intfc, final MethodHandle target) { if (!intfc.isInterface() || !Modifier.isPublic(intfc.getModifiers())) throw new IllegalArgumentException("not a public interface: " + intfc.getName()); final Method[] methods = getSingleNameMethods(intfc); if (methods == null) throw new IllegalArgumentException("not a single-method interface: " + intfc.getName()); final MethodHandle[] vaTargets = new MethodHandle[methods.length]; for (int i = 0; i < methods.length; i++) { Method sm = methods[i]; MethodType smMT = MethodType.methodType(sm.getReturnType(), sm.getParameterTypes()); MethodHandle checkTarget = target.asType(smMT); // make throw WMT checkTarget = checkTarget.asType(checkTarget.type().changeReturnType(Object.class)); vaTargets[i] = checkTarget.asSpreader(Object[].class, smMT.parameterCount()); } return intfc.cast( Proxy.newProxyInstance( intfc.getClassLoader(), new Class[] {intfc, WrapperInstance.class}, new InvocationHandler() { private Object getArg(String name) { if ((Object) name == "getWrapperInstanceTarget") return target; if ((Object) name == "getWrapperInstanceType") return intfc; throw new AssertionError(); } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { for (int i = 0; i < methods.length; i++) { if (method.equals(methods[i])) return vaTargets[i].invokeExact(args); } if (method.getDeclaringClass() == WrapperInstance.class) return getArg(method.getName()); if (isObjectMethod(method)) return callObjectMethod(this, method, args); throw new InternalError("bad proxy method: " + method); } })); }
public <T extends Widget> T getparent(Class<T> cl) { for (Widget w = this; w != null; w = w.parent) { if (cl.isInstance(w)) return (cl.cast(w)); } return (null); }
/** * Creates a strongly-typed proxy to access values in this {@link Dom} object, by using the * specified interface type as the proxy type. */ public <T extends ConfigBeanProxy> T createProxy(final Class<T> proxyType) { ConfigBeanProxy retVal = proxyCache.compute(proxyType); return proxyType.cast(retVal); }
/** * Assembles a bean from an XML file. * * @param <T> the expected object type * @param file the path to the XML file * @param type the expected object type * @return an object assembled from this XML file * @throws SAXException if the internal SAX parser fails * @throws IOException if any IO errors occur */ public <T> T build(String file, Class<T> type) throws SAXException, IOException { _parser.parse(new File(file), this); return type.cast(getBean()); }
/** * Assembles a bean from an XML stream. * * @param <T> the expected object type * @param stream the XML input stream * @param type the expected object type * @return an object assembled from this XML stream * @throws SAXException if the internal SAX parser fails * @throws IOException if any IO errors occur */ public <T> T build(InputStream stream, Class<T> type) throws SAXException, IOException { _parser.parse(stream, this); return type.cast(getBean()); }