Dopasowanie typów (refleksja+generyczne)

Dopasowanie typów (refleksja+generyczne)
A1
  • Rejestracja:prawie 8 lat
  • Ostatnio:ponad 2 lata
  • Postów:7
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ć:

Kopiuj
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:

Kopiuj
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:

Kopiuj
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();
	}
}
AreQ212
  • Rejestracja:ponad 11 lat
  • Ostatnio:ponad 5 lat
  • Postów:29
1

Dodaj konstruktor bezargumentowy w klasie Human.

edytowany 1x, ostatnio: AreQ212
A1
  • Rejestracja:prawie 8 lat
  • Ostatnio:ponad 2 lata
  • Postów:7
0

Dziękuję. Teraz wszystko działa.

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.