2 * Copyright (c) 2010-2023 Contributors to the openHAB project
4 * See the NOTICE file(s) distributed with this work for additional
7 * This program and the accompanying materials are made available under the
8 * terms of the Eclipse Public License 2.0 which is available at
9 * http://www.eclipse.org/legal/epl-2.0
11 * SPDX-License-Identifier: EPL-2.0
13 package org.openhab.binding.lifx.internal.dto;
15 import java.lang.reflect.Constructor;
16 import java.lang.reflect.Field;
17 import java.nio.ByteBuffer;
19 import org.eclipse.jdt.annotation.NonNullByDefault;
22 * A generic handler that dynamically creates "standard" packet instances.
25 * Packet types must have an empty constructor and cannot require any
26 * additional logic (other than parsing).
28 * @param <T> the packet subtype this handler constructs
30 * @author Tim Buckley - Initial contribution
31 * @author Karel Goderis - Enhancement for the V2 LIFX Firmware and LAN Protocol Specification
34 public class GenericHandler<T extends Packet> implements PacketHandler<T> {
36 private Constructor<T> constructor;
38 private boolean typeFound;
41 public boolean isTypeFound() {
45 public int getType() {
49 public GenericHandler(Class<T> clazz) {
51 constructor = clazz.getConstructor();
52 } catch (NoSuchMethodException ex) {
53 throw new IllegalArgumentException("Packet class cannot be handled by GenericHandler", ex);
57 Field typeField = clazz.getField("TYPE");
58 type = (int) typeField.get(null);
60 } catch (NoSuchFieldException | IllegalAccessException ex) {
67 public T handle(ByteBuffer buf) {
69 T ret = constructor.newInstance();
72 } catch (ReflectiveOperationException ex) {
73 throw new IllegalArgumentException("Unable to instantiate empty packet", ex);