Skip to content

Instantly share code, notes, and snippets.

@tarivs
Created April 24, 2023 12:33
Show Gist options
  • Save tarivs/36c61ccb65e3830174debb6d5d6a712e to your computer and use it in GitHub Desktop.
Save tarivs/36c61ccb65e3830174debb6d5d6a712e to your computer and use it in GitHub Desktop.
package com.data;
public interface Animal {
public String getName();
}
/**/
class Cat implements Animal {
private String name;
public Cat() {
}
public Cat(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
}
/**/
public class Dog implements Animal {
private String name;
private Integer age;
public Dog() {}
public Dog(String name, Integer age) {
this.name = name;
this.age = age;
}
@Override
public String getName() {
return null;
}
}
/* 重点这里 */
public class AnimalInfo<T extends Animal> {
private final T animal;
public AnimalInfo(T animal) {
this.animal = animal;
}
public Set<String> process() {
return Arrays.stream(this.animal.getClass().getDeclaredFields()).map(Field::getName).collect(Collectors.toSet());
}
}
/**/
public class Main {
public static void main(String[] args) {
AnimalInfo<Cat> catInfo = new AnimalInfo<>(new Cat("tom"));
Set<String> catFields = catInfo.process();
System.out.println(catFields);
AnimalInfo<Dog> dogInfo = new AnimalInfo<>(new Dog("jim", 8));
Set<String> dogFields = dogInfo.process();
System.out.println(dogFields);
}
}
/*打印结果*/
// [name]
// [name, age]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment