Here you can find the source of invokeNoArgs(Object instance, Method method, Class
Parameter | Description |
---|---|
instance | Instance to use as 'this' for invocation. |
method | Method to invoke. |
returnType | Return type to cast the method's return value. |
T | Return type. |
Parameter | Description |
---|
public static <T> T invokeNoArgs(Object instance, Method method, Class<T> returnType)
//package com.java2s; /****************************************************************************** * Copyright (C) 2014 Yevgeny Krasik * * * * 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. * ******************************************************************************/ import java.lang.reflect.Method; public class Main { private static final Object[] NO_ARGS = {}; /**// w ww .j ava2 s . co m * Invokes the method, using the provided instance as 'this', and casts the return value to the provided return type. * Method must be no-args and return the correct type. * * @param instance Instance to use as 'this' for invocation. * @param method Method to invoke. * @param returnType Return type to cast the method's return value. * @param <T> Return type. * @return The result of invoking the no-args method, cast to the provided type. * @throws java.lang.IllegalStateException If an error occurred invoking the method. */ public static <T> T invokeNoArgs(Object instance, Method method, Class<T> returnType) { try { if (!method.isAccessible()) { method.setAccessible(true); } final Object returnValue = method.invoke(instance, NO_ARGS); return returnType.cast(returnValue); } catch (Exception e) { final String message = String.format("Error invoking no-args method: class=%s, method=%s", method.getDeclaringClass(), method.getName()); throw new IllegalStateException(message, e); } } }