/*
 * $Header: /home/cvspublic/jakarta-slide/proposals/tamino/src/util/org/apache/slide/util/reflect/Meth.java,v 1.1 2004/03/25 16:18:12 juergen Exp $
 * $Revision: 1.1 $
 * $Date: 2004/03/25 16:18:12 $
 *
 * ====================================================================
 *
 * Copyright 1999-2004 The Apache Software Foundation.
 *
 * 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 org.apache.slide.util.reflect;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;
import org.apache.slide.util.XAssertionFailed;

/**
 * Wraps a Java Method to make it useable as a Function. Both static
 * and non-static methods can be wrapped. Java Method means
 * java.lang.reflect.Method.
 */
public class Meth extends Function {
    private java.lang.reflect.Method meth;
    
    public Meth(java.lang.reflect.Method meth) {
        int modif;
        
        modif = meth.getModifiers();
        if (Modifier.isAbstract(modif) || !Modifier.isPublic(modif)) {
            throw new IllegalArgumentException();
        }
        
        this.meth = meth;
    }
    
    public int getModifiers() {
        return meth.getModifiers();
    }

    public String getQName() {
        return meth.getName();
    }
    
    public Class getReturnType() {
        return meth.getReturnType();
    }
    
    public Class[] getParameterTypes() {
        Class[] formals;
        
        formals = meth.getParameterTypes();
        if (!isStatic()) {
            formals = (Class[]) Util.cons(meth.getDeclaringClass(), formals);
        }
        return formals;
    }
    
    public Object invoke(Object[] actuals) throws InvocationTargetException {
        Object dest;
        
        if (isStatic()) {
            dest = null;
        } else {
            dest = actuals[0];
            actuals = Util.cdr(actuals);
        }
        try {
            return meth.invoke(dest, actuals);
        } catch (IllegalAccessException e) {
            throw new XAssertionFailed(e);
        }
    }
}
