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
- newInstance(String name)
- newInstance(String name, ClassLoader loader)
- newInstance(String s)
- newInstance(String type)
- newInstance(String type, Class cast)
- newInstance(T obj, Class> argType, Object arg)
- newInstance(Type type)
- newInstance(Type type)
- newInstance(Type type)