Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Generic class<T> - get T info or class name

  1. #1
    Junior Member
    Join Date
    Dec 2022
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Generic class<T> - get T info or class name

    Hello, i need help

    Question: Get T info or name, who is T ?

    I summarized all the code.... but the goal is to know which annotations T has

    -----code for demo problem ----------------------
    public class Xpto {}

    public class class ModelHelper<T> {
    public String getTclassName() {
    String className = this.getName(); //OK for class
    String tName = T.getName() //?!?!??!??!?; Problem !!!! how do i get T name?
    return tName;
    }
    }

    void maiin() {
    ModelHelper<Xpto > modelHelper = new ModelHelper<>();
    String className = modelHelper.getTclassName();
    }
    ----------------------------------------

    Note: I don't look for solutions like : "getTclassName(Class<T> clazz)" because the class "ModelHelper<T>" has an obligation to know who T is!!!

    Thanks for help

  2. #2
    Junior Member
    Join Date
    Feb 2023
    Location
    Hungary
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: Generic class<T> - get T info or class name

    I do not think this is possible.
    It wouldn't be a problem during compile, but in runtime the type of T is unknown. Thank to java's type erasure of generics to provide backward compatibility.
    As I know java has generics since 1.5 and this plagues us since then.

Similar Threads

  1. Replies: 7
    Last Post: March 10th, 2014, 04:28 PM
  2. need to make basic class and implementation class (base class without void main)
    By javanewbie101 in forum Object Oriented Programming
    Replies: 1
    Last Post: September 19th, 2012, 08:03 PM
  3. having problem declaring a generic type array in OrderSet class
    By mia_tech in forum What's Wrong With My Code?
    Replies: 2
    Last Post: July 10th, 2012, 06:39 PM
  4. Replies: 3
    Last Post: June 17th, 2012, 06:22 PM
  5. generic class
    By fireatmuself in forum Collections and Generics
    Replies: 4
    Last Post: November 17th, 2009, 06:06 AM