Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright (C) 2012 The Guava Authors
   *
   * 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 com.google.common.reflect;
 
 import static com.google.common.base.Preconditions.checkNotNull;
 
 
 
 import  javax.annotation.Nullable;

Wrapper around either a Method or a Constructor. Convenience API is provided to make common reflective operation easier to deal with, such as isPublic, getParameters etc.

In addition to convenience methods, TypeToken.method and TypeToken.constructor will resolve the type parameters of the method or constructor in the context of the owner type, which may be a subtype of the declaring class. For example:

   Method getMethod = List.class.getMethod("get", int.class);
   Invokable<List<String>, ?> invokable = new TypeToken<List<String>>() {.method(getMethod);
   assertEquals(TypeToken.of(String.class), invokable.getReturnType()); // Not Object.class!
   assertEquals(new TypeToken<List<String>>() {}, invokable.getOwnerType());}

Parameters:
<T> the type that owns this method or constructor.
<R> the return type of (or supertype thereof) the method or the declaring type of the constructor.
Author(s):
Ben Yu
Since:
14.0
 
 public abstract class Invokable<T, R> extends Element implements GenericDeclaration {
 
   <M extends AccessibleObject & MemberInvokable(M member) {
     super(member);
   }

  
Returns Invokable of method.
 
   public static Invokable<?, Objectfrom(Method method) {
     return new MethodInvokable<Object>(method);
   }

  
Returns Invokable of constructor.
 
   public static <T> Invokable<T, T> from(Constructor<T> constructor) {
     return new ConstructorInvokable<T>(constructor);
   }

  
Returns true if this is an overridable method. Constructors, private, static or final methods, or methods declared by final classes are not overridable.
 
   public abstract boolean isOverridable();

  
Returns true if this was declared to take a variable number of arguments.
 
   public abstract boolean isVarArgs();

  
Invokes with receiver as 'this' and args passed to the underlying method and returns the return value; or calls the underlying constructor with args and returns the constructed instance.

Throws:
IllegalAccessException if this Constructor object enforces Java language access control and the underlying method or constructor is inaccessible.
IllegalArgumentException if the number of actual and formal parameters differ; if an unwrapping conversion for primitive arguments fails; or if, after possible unwrapping, a parameter value cannot be converted to the corresponding formal parameter type by a method invocation conversion.
InvocationTargetException if the underlying method or constructor throws an exception.
 
   // All subclasses are owned by us and we'll make sure to get the R type right.
   @SuppressWarnings("unchecked")
  public final R invoke(@Nullable T receiverObject... args)
    return (R) invokeInternal(receivercheckNotNull(args));
  }

  
Returns the return type of this Invokable.
  // All subclasses are owned by us and we'll make sure to get the R type right.
  @SuppressWarnings("unchecked")
  public final TypeToken<? extends R> getReturnType() {
    return (TypeToken<? extends R>) TypeToken.of(getGenericReturnType());
  }

  
Returns all declared parameters of this Invokable. Note that if this is a constructor of a non-static inner class, unlike Constructor.getParameterTypes, the hidden this parameter of the enclosing class is excluded from the returned parameters.
  public final ImmutableList<ParametergetParameters() {
    Type[] parameterTypes = getGenericParameterTypes();
    Annotation[][] annotations = getParameterAnnotations();
    ImmutableList.Builder<Parameterbuilder = ImmutableList.builder();
    for (int i = 0; i < parameterTypes.lengthi++) {
      builder.add(new Parameter(
          thisi, TypeToken.of(parameterTypes[i]), annotations[i]));
    }
    return builder.build();
  }

  
Returns all declared exception types of this Invokable.
  public final ImmutableList<TypeToken<? extends Throwable>> getExceptionTypes() {
    ImmutableList.Builder<TypeToken<? extends Throwable>> builder = ImmutableList.builder();
    for (Type type : getGenericExceptionTypes()) {
       // getGenericExceptionTypes() will never return a type that's not exception
      @SuppressWarnings("unchecked")
      TypeToken<? extends ThrowableexceptionType = (TypeToken<? extends Throwable>)
          TypeToken.of(type);
      builder.add(exceptionType);
    }
    return builder.build();
  }

  
Explicitly specifies the return type of this Invokable. For example:
   Method factoryMethod = Person.class.getMethod("create");
   Invokable<?, Person> factory = Invokable.of(getNameMethod).returning(Person.class);
 
  public final <R1 extends R> Invokable<T, R1> returning(Class<R1> returnType) {
    return returning(TypeToken.of(returnType));
  }

  
Explicitly specifies the return type of this Invokable.
  public final <R1 extends R> Invokable<T, R1> returning(TypeToken<R1> returnType) {
    if (!returnType.isAssignableFrom(getReturnType())) {
      throw new IllegalArgumentException(
          "Invokable is known to return " + getReturnType() + ", not " + returnType);
    }
    @SuppressWarnings("unchecked"// guarded by previous check
    Invokable<T, R1> specialized = (Invokable<T, R1>) this;
    return specialized;
  }
  @SuppressWarnings("unchecked"// The declaring class is T's raw class, or one of its supertypes.
  @Override public final Class<? super T> getDeclaringClass() {
    return (Class<? super T>) super.getDeclaringClass();
  }

  
Returns the type of T.
  // Overridden in TypeToken#method() and TypeToken#constructor()
  @SuppressWarnings("unchecked"// The declaring class is T.
  public TypeToken<T> getOwnerType() {
    return (TypeToken<T>) TypeToken.of(getDeclaringClass());
  }
  abstract Object invokeInternal(@Nullable Object receiverObject[] args)
  abstract Type[] getGenericParameterTypes();

  
This should never return a type that's not a subtype of Throwable.
  abstract Type[] getGenericExceptionTypes();
  abstract Type getGenericReturnType();
  
  static class MethodInvokable<T> extends Invokable<T, Object> {
    private final Method method;
    MethodInvokable(Method method) {
      super(method);
      this. = method;
    }
    @Override final Object invokeInternal(@Nullable Object receiverObject[] args)
      return .invoke(receiverargs);
    }
      return .getGenericReturnType();
    }
      return .getGenericParameterTypes();
    }
      return .getGenericExceptionTypes();
    }
      return .getParameterAnnotations();
    }
    @Override public final TypeVariable<?>[] getTypeParameters() {
      return .getTypeParameters();
    }
    @Override public final boolean isOverridable() {
      return  !(isFinal() || isPrivate() || isStatic()
          || Modifier.isFinal(getDeclaringClass().getModifiers()));
    }
    @Override public final boolean isVarArgs() {
      return .isVarArgs();
    }
  }
  static class ConstructorInvokable<T> extends Invokable<T, T> {
    private final Constructor<?> constructor;
    ConstructorInvokable(Constructor<?> constructor) {
      super(constructor);
      this. = constructor;
    }
    @Override final Object invokeInternal(@Nullable Object receiverObject[] args)
      try {
        return .newInstance(args);
      } catch (InstantiationException e) {
        throw new RuntimeException( + " failed."e);
      }
    }
      return .getDeclaringClass();
    }
      Type[] types = .getGenericParameterTypes();
      Class<?> declaringClass = .getDeclaringClass();
      if (!Modifier.isStatic(declaringClass.getModifiers())
          && declaringClass.getEnclosingClass() != null) {
        if (types.length == .getParameterTypes().length) {
          // first parameter is the hidden 'this'
          return Arrays.copyOfRange(types, 1, types.length);
        }
      }
      return types;
    }
    }
    }
    @Override public final TypeVariable<?>[] getTypeParameters() {
      return .getTypeParameters();
    }
    @Override public final boolean isOverridable() {
      return false;
    }
    @Override public final boolean isVarArgs() {
      return .isVarArgs();
    }
  }
New to GrepCode? Check out our FAQ X