Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;

import java.lang.reflect.*;

public class Main {
    public static <S, T> T castObject(S source, Class<T> targetClass)
            throws IllegalAccessException, InstantiationException {
        T newInstance = targetClass.newInstance();
        for (Field field : source.getClass().getDeclaredFields()) {
            for (Field fieldTarget : targetClass.getDeclaredFields()) {
                if (isFieldsEqual(field, fieldTarget)) {
                    setField(getField(field, source), fieldTarget, newInstance);
                }
            }
        }
        return newInstance;
    }

    public static <T extends Object> T newInstance(Class<T> cl, Object... args) throws NoSuchMethodException,
            IllegalAccessException, InvocationTargetException, InstantiationException {
        Constructor<T> constructor = cl.getDeclaredConstructor(new Class[0]);
        boolean accessible = constructor.isAccessible();
        constructor.setAccessible(true);
        T t = constructor.newInstance(args);
        constructor.setAccessible(accessible);
        return t;
    }

    private static boolean isFieldsEqual(Field one, Field two) {
        return one.getName().equals(two.getName()) && one.getType().equals(two);
    }

    public static void setField(Object value, Field field, Object target) {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object result = null;
        try {
            field.set(target, value);
        } catch (IllegalAccessException e) {
            // ignore
        }
        field.setAccessible(accessible);
    }

    public static Object getField(Field field, Object source) {
        boolean accessible = field.isAccessible();
        field.setAccessible(true);
        Object result = null;
        try {
            result = field.get(source);
        } catch (IllegalAccessException e) {
            // ignore
        }
        field.setAccessible(accessible);
        return result;
    }
}