Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

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

import java.lang.reflect.Type;

public class Main {
    public static void setField(Object object, String fieldName, Object fieldValue) {
        Class<?> objectClass = object.getClass();
        if (objectClass != null) {
            try {
                Field field = objectClass.getDeclaredField(fieldName);
                field.setAccessible(true);
                Type type = field.getGenericType();

                //This is bad, but dear God I can't figure out how to convert a runtime Type to its actual type through reflection. I know how in C#....
                if (type.toString().toLowerCase().contains("short")) {
                    fieldValue = Short.parseShort((String) fieldValue);
                }

                else if (type.toString().toLowerCase().contains("integer")) {
                    fieldValue = Integer.parseInt((String) fieldValue);
                }

                else if (type.toString().toLowerCase().contains("long")) {
                    fieldValue = Long.parseLong((String) fieldValue);
                }

                else if (type.toString().toLowerCase().contains("boolean")) {
                    fieldValue = "1".equals(fieldValue); //Java, you're the worst language. And SQLite isn't helping.
                }

                field.set(object, fieldValue);
            }

            catch (NoSuchFieldException e) {
                return;
            }

            catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}