0

I would like to get E class name in String value with java reflection. For example, if i create Node typed in Person, getClassName() has to return "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;
}
}
  • I don't quite get your example and requirements, can you elaborate? How would `Person` and `Node` (which I guess you mean) be related? Where is `Node` used and how? – Thomas Jan 10 '17 at 09:48
  • Possible duplicate of [How to get a class instance of generics type T](http://stackoverflow.com/questions/3437897/how-to-get-a-class-instance-of-generics-type-t) – shmosel Jan 10 '17 at 09:49
  • Node is a simply object that has got property but it isn't related with values that extend AbstractNode – Simon Calabrese Jan 10 '17 at 09:51
  • It really depends on how you use `Node`, e.g. if the node contains an element of type `E` you could just call `getClass()` on that, if you use concrete subclasses like `PersonNode extends Node` you can use reflection to get the type parameter etc. (note that due to type erasure that doesn't work with variables of type `Node` in most cases). – Thomas Jan 10 '17 at 10:06

1 Answers1

0

Add a field to your Node class

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:

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.

Arnab Datta
  • 5,356
  • 10
  • 41
  • 67