Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
import android.os.Bundle;
import android.support.v4.app.Fragment;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Main {
    /**
     * Tries to initialize fragment of type clazz by one of methods:
     * init(Bundle), init().
     *
     * @param clazz type of fragment to initialize
     * @param data data to initialize fragment with
     * @param <T> child of Fragment class
     * @return initialized fragment or null
     */
    private static <T extends Fragment> T initFragment(Class<T> clazz, Bundle data) {

        final String INIT = "newInstance";

        try {
            Method init;
            Object fragment;

            if (data != null) {
                init = clazz.getMethod(INIT, Bundle.class);
                fragment = init.invoke(null, data);

            } else {
                init = clazz.getMethod(INIT);
                fragment = init.invoke(null);
            }
            return clazz.cast(fragment);

        } catch (NoSuchMethodException | IllegalAccessException | IllegalArgumentException
                | InvocationTargetException | ClassCastException e) {
            e.printStackTrace();
        }
        return null;
    }
}