import
java.lang.reflect.InvocationTargetException;
import
java.lang.reflect.Method;
import
java.util.ArrayList;
import
java.util.Arrays;
import
java.util.List;
class
GfG
implements
Cloneable {
String username;
String msg;
GfG(String username, String msg)
{
this
.username = username;
this
.msg = msg;
}
@Override
public
String toString()
{
return
"\nHello "
+ username
+
"!\n"
+ msg +
"\n"
;
}
@Override
protected
Object clone()
throws
CloneNotSupportedException
{
return
new
GfG(username, msg);
}
}
class
ListUtils {
public
static
<T
extends
Cloneable> List<T>
clone(List<T> original)
throws
NoSuchMethodException,
InvocationTargetException,
IllegalAccessException
{
if
(original ==
null
|| original.size() ==
0
) {
return
new
ArrayList<>();
}
Method method
= original.get(
0
)
.getClass()
.getDeclaredMethod(
"clone"
);
List<T> clone =
new
ArrayList<>();
for
(T item : original) {
clone.add((T)method.invoke(item));
}
return
clone;
}
public
static
void
main(String[] args)
{
List<GfG> original
= Arrays.asList(
new
GfG(
"Geeks"
,
"GeeksForGeeks"
),
new
GfG(
"GFG"
,
"A computer science portal for geeks"
));
List<GfG> cloned_list =
null
;
try
{
cloned_list = clone(original);
}
catch
(NoSuchMethodException e) {
e.printStackTrace();
}
catch
(InvocationTargetException e) {
e.printStackTrace();
}
catch
(IllegalAccessException e) {
e.printStackTrace();
}
System.out.println(cloned_list);
}
}