Java Class New Instance newInstance(T obj)

Here you can find the source of newInstance(T obj)

Description

Generic newInstance that tries to clone an object.

License

Open Source License

Parameter

Parameter Description
T Object type, generic
obj Master copy - must not be null.

Exception

Parameter Description
InstantiationException on error
IllegalAccessException on error
InvocationTargetException on error
NoSuchMethodException on error

Return

New instance, if possible

Declaration

@SuppressWarnings("unchecked")
public static <T> T newInstance(T obj) throws InstantiationException,
        IllegalAccessException, InvocationTargetException,
        NoSuchMethodException 

Method Source Code

//package com.java2s;
/*/*  www.  ja  v  a2s .  c  o m*/
 This file is part of ELKI:
 Environment for Developing KDD-Applications Supported by Index-Structures

 Copyright (C) 2013
 Ludwig-Maximilians-Universit?t M?nchen
 Lehr- und Forschungseinheit f?r Datenbanksysteme
 ELKI Development Team

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU Affero General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU Affero General Public License for more details.

 You should have received a copy of the GNU Affero General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

import java.lang.reflect.InvocationTargetException;

public class Main {
    /**
     * Generic newInstance that tries to clone an object.
     * 
     * @param <T> Object type, generic
     * @param obj Master copy - must not be null.
     * @return New instance, if possible
     * @throws InstantiationException on error
     * @throws IllegalAccessException on error
     * @throws InvocationTargetException on error
     * @throws NoSuchMethodException on error
     */
    @SuppressWarnings("unchecked")
    public static <T> T newInstance(T obj) throws InstantiationException,
            IllegalAccessException, InvocationTargetException,
            NoSuchMethodException {
        try {
            Object n = obj.getClass().getConstructor().newInstance();
            return (T) n;
        } catch (NullPointerException e) {
            throw new IllegalArgumentException(
                    "Null pointer exception in newInstance()", e);
        }
    }
}

Related

  1. newInstance(String name)
  2. newInstance(String name, ClassLoader loader)
  3. newInstance(String s)
  4. newInstance(String type)
  5. newInstance(String type, Class cast)
  6. newInstance(T obj, Class argType, Object arg)
  7. newInstance(Type type)
  8. newInstance(Type type)
  9. newInstance(Type type)