get Type For Field via reflection - Android java.lang.reflect

Android examples for java.lang.reflect:Field

Description

get Type For Field via reflection

Demo Code

/*//from  w  w  w. j av a  2s.c  o  m

This file is part of Roboject

Copyright (c) 2010-2011 akquinet A.G.

Contact:  http://www.akquinet.de/en

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.java2s;

import android.content.res.ColorStateList;

import android.graphics.drawable.Drawable;
import android.view.animation.Animation;

import java.lang.reflect.Field;

public class Main {
    public static String getTypeForField(Field field) {
        Class type = field.getType();
        // Animation
        if (type.isAssignableFrom(Animation.class))
            return "anim";
        // Color State List
        else if (type.isAssignableFrom(ColorStateList.class))
            return "color";
        // Drawable
        else if (type.isAssignableFrom(Drawable.class))
            return "drawable";
        // String
        else if (type.isAssignableFrom(String.class))
            return "string";
        // String Array
        else if (type.isArray())
            return "array";
        // TODO: Recognize plural strings if possible
        //        else if (type.isAssignableFrom(String.class))
        //            return "plural";
        // Boolean
        else if (type.isAssignableFrom(Boolean.TYPE)
                || type.isAssignableFrom(Boolean.class))
            return "bool";
        // Integer
        else if (type.isAssignableFrom(Integer.TYPE)
                || type.isAssignableFrom(Integer.class))
            return "integer";
        // Dimen
        else if (type.isAssignableFrom(Float.TYPE)
                || type.isAssignableFrom(Float.class))
            return "dimen";

        throw new RuntimeException("No suitable type found for "
                + field.getName() + "of class " + type.getName());
    }
}

Related Tutorials