2 * Copyright (c) 2014 Cisco Systems, Inc. and others. All rights reserved.
4 * This program and the accompanying materials are made available under the
5 * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6 * and is available at http://www.eclipse.org/legal/epl-v10.html
8 package org.opendaylight.yangtools.binding.data.codec.impl;
10 import com.google.common.base.Preconditions;
11 import com.google.common.base.Throwables;
12 import java.lang.invoke.MethodHandle;
13 import java.lang.invoke.MethodHandles;
14 import java.lang.invoke.MethodHandles.Lookup;
15 import java.lang.invoke.MethodType;
16 import java.lang.reflect.Method;
17 import org.opendaylight.yangtools.concepts.Codec;
19 final class UnionValueOptionContext {
20 private static final Lookup LOOKUP = MethodHandles.publicLookup();
21 private static final MethodType OBJECT_TYPE = MethodType.methodType(Object.class, Object.class);
22 private final Class<?> bindingType;
23 // FIXME: migrate to invocation
24 private final MethodHandle getter;
25 private final Codec<Object,Object> codec;
27 UnionValueOptionContext(final Class<?> valueType, final Method getter, final Codec<Object, Object> codec) {
28 this.bindingType = Preconditions.checkNotNull(valueType);
29 this.codec = Preconditions.checkNotNull(codec);
32 this.getter = LOOKUP.unreflect(getter).asType(OBJECT_TYPE);
33 } catch (IllegalAccessException e) {
34 throw new IllegalStateException("Failed to access method " + getter, e);
38 Object serialize(final Object input) {
39 final Object baValue = getValueFrom(input);
40 if (baValue == null) {
44 return codec.serialize(baValue);
47 Object getValueFrom(final Object input) {
49 return getter.invokeExact(input);
50 } catch (Throwable e) {
51 throw Throwables.propagate(e);
56 public int hashCode() {
57 return bindingType.hashCode();
61 public boolean equals(final Object obj) {
65 if (!(obj instanceof UnionValueOptionContext)) {
69 final UnionValueOptionContext other = (UnionValueOptionContext) obj;
70 return bindingType.equals(other.bindingType);