Dopasowanie typów (refleksja+generyczne)

0

Witajcie!
Przerabiam sobie książkę "Java. Podstawy" i natrafiłem na niezmiernie krótki podrozdział prezentujący tematykę podaną w tytule wątku. Niestety, mój kod nie chce działać:

public class Refleksja 
{
	public static <T> Pair<T> makePair(Class<T> c) throws InstantiationException, IllegalAccessException
	{
		return new Pair<T>(c.newInstance(), c.newInstance());
	}
	
	public static void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException
	{
		Pair<Human> humans = makePair(Human.class);
		System.out.println(humans);
	}
}

Wyrzuca mi następujący stacktrace:

Exception in thread "main" java.lang.InstantiationException: Human
	at java.lang.Class.newInstance(Unknown Source)
	at Refleksja.makePair(Refleksja.java:5)
	at Refleksja.main(Refleksja.java:10)
Caused by: java.lang.NoSuchMethodException: Human.<init>()
	at java.lang.Class.getConstructor0(Unknown Source)
	... 3 more

Rozumiem, że problem dotyczy implementacji klasy Human, która jest następująca:

public class Human {
	private String name;
	private int age;
	
	public Human(String name, int age) {
		this.name = name;
		this.age = age;
	}
	
	public String getName() {
		return name;
	}
	
	public int getAge() {
		return age;
	}
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setAge(int age) {
		this.age = age;
	}
	
	public String toString() {
		return this.getName()+" , "+this.getAge();
	}
}
1

Dodaj konstruktor bezargumentowy w klasie Human.

0

Dziękuję. Teraz wszystko działa.

1 użytkowników online, w tym zalogowanych: 0, gości: 1