calculate hash Code by reflection on object - Android java.lang.reflect

Android examples for java.lang.reflect:Java Bean

Description

calculate hash Code by reflection on object

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

public class Main {
    public static int hashCode(Object object) {
        final int prime = 31;
        int result = 1;
        Field[] fields = object.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);//from  w  ww .  ja v  a 2s . c  o m
            Object value;
            try {
                value = field.get(object);
                result = prime * result
                        + ((value == null) ? 0 : value.hashCode());
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}

Related Tutorials