Java tutorial
//package com.java2s; /* * Copyright 2011-2013 HTTL Team. * * 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.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; public class Main { public static List<Field> getPublicFields(Class<?> clazz) { List<Field> publicList = new ArrayList<Field>(); List<Field> accessibleList = getAccessibleFields(clazz, Object.class); for (Field f : accessibleList) { if (Modifier.isPublic(f.getModifiers()) == true) { publicList.add(f); } } accessibleList.clear(); return publicList; } public static List<Field> getAccessibleFields(Class<?> clazz) { return getAccessibleFields(clazz, Object.class); } public static List<Field> getAccessibleFields(Class<?> clazz, Class<?> limit) { Package topPackage = clazz.getPackage(); List<Field> fieldList = new ArrayList<Field>(); int topPackageHash = topPackage == null ? 0 : topPackage.hashCode(); boolean top = true; do { if (clazz == null) { break; } Field[] declaredFields = clazz.getDeclaredFields(); for (Field field : declaredFields) { if (top == true) { // add all top declared fields fieldList.add(field); continue; } int modifier = field.getModifiers(); if (Modifier.isPrivate(modifier) == true) { continue; // ignore super private fields } if (Modifier.isPublic(modifier) == true) { addFieldIfNotExist(fieldList, field); // add super public methods continue; } if (Modifier.isProtected(modifier) == true) { addFieldIfNotExist(fieldList, field); // add super protected methods continue; } // add super default methods from the same package Package pckg = field.getDeclaringClass().getPackage(); int pckgHash = pckg == null ? 0 : pckg.hashCode(); if (pckgHash == topPackageHash) { addFieldIfNotExist(fieldList, field); } } top = false; } while ((clazz = clazz.getSuperclass()) != limit); return fieldList; } private static void addFieldIfNotExist(List<Field> allFields, Field newField) { for (Field f : allFields) { if (compareSignatures(f, newField) == true) { return; } } allFields.add(newField); } private static boolean compareSignatures(Field first, Field second) { return first.getName().equals(second.getName()); } }