alvinalexander.com | career | drupal | java | mac | mysql | perl | scala | uml | unix  

Java example source code file (InterceptorFactory.java)

This example Java source code file (InterceptorFactory.java) is included in the alvinalexander.com "Java Source Code Warehouse" project. The intent of this project is to help you "Learn Java by Example" TM.

Learn more about this Java project at its project page.

Java - Java tags/keywords

intercept, interceptoradapter, interceptorfactory, ioexception, jsonpostdeserializer, override, runtimeexception, suppresswarnings, typeadapter, typeadapterfactory, typetoken

The InterceptorFactory.java Java example source code

package com.google.gson.interceptors;

import com.google.gson.Gson;
import com.google.gson.TypeAdapter;
import com.google.gson.TypeAdapterFactory;
import com.google.gson.reflect.TypeToken;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;

/**
 * A type adapter factory that implements {@code @Intercept}.
 */
public final class InterceptorFactory implements TypeAdapterFactory {
  public <T> TypeAdapter create(Gson gson, TypeToken type) {
    Intercept intercept = type.getRawType().getAnnotation(Intercept.class);
    if (intercept == null) {
      return null;
    }

    TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
    return new InterceptorAdapter<T>(delegate, intercept);
  }

  static class InterceptorAdapter<T> extends TypeAdapter {
    private final TypeAdapter<T> delegate;
    private final JsonPostDeserializer<T> postDeserializer;

    @SuppressWarnings("unchecked") // ?
    public InterceptorAdapter(TypeAdapter<T> delegate, Intercept intercept) {
      try {
        this.delegate = delegate;
        this.postDeserializer = intercept.postDeserialize().newInstance();
      } catch (Exception e) {
        throw new RuntimeException(e);
      }
    }

    @Override public void write(JsonWriter out, T value) throws IOException {
      delegate.write(out, value);
    }

    @Override public T read(JsonReader in) throws IOException {
      T result = delegate.read(in);
      postDeserializer.postDeserialize(result);
      return result;
    }
  }
}

Other Java examples (source code examples)

Here is a short list of links related to this Java InterceptorFactory.java source code file:

... this post is sponsored by my books ...

#1 New Release!

FP Best Seller

 

new blog posts

 

Copyright 1998-2021 Alvin Alexander, alvinalexander.com
All Rights Reserved.

A percentage of advertising revenue from
pages under the /java/jwarehouse URI on this website is
paid back to open source projects.