简体   繁体   English

[JAVA]如何获取通用类的键入名称

[英][JAVA]How to get generic class typed name

I would like to get E class name in String value with java reflection. 我想用java反射获取String值中的E类名称。 For example, if i create Node typed in Person, getClassName() has to return "Person" 例如,如果我创建键入Person的Node,则getClassName()必须返回“ Person”

Someone can help me? 有人可以帮我吗?

public class Node<E extends AbstractNode> {

String getClassName() {
    String name = ?? 
}

private String alias;

public Node() {

}
}


public abstract class AbstractNode {
}


public class Person extends AbstractNode {
private String name;
private String surname;

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

public String getSurname() {
    return surname;
}

public void setSurname(String surname) {
    this.surname = surname;
}
}

Add a field to your Node class 将字段添加到您的Node

private static final Class<T> type;

And add this to your constructor signature 并将其添加到您的构造函数签名中

public Node(Class type) {
   this.type = type;
}

Lastly, create the getClassName method in your Node class: 最后,在您的Node类中创建getClassName方法:

public String getClassName(){
    return this.type.getName();
}

Edit: As a sidenote, your AbstractNode class is not really necessary (it doesn't do anything) and therefore neither is the extend in Person. 编辑:作为一个旁注,您的AbstractNode类并不是真正必需的(它不执行任何操作),因此Person中的extend也不是。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM