How to access generic info on class

Let's say I have a class like this:
class HelloWorld<T extends World> {

private T world;

public(T world) {
this.world = world;
}

T get() {
return world;
}
}
class HelloWorld<T extends World> {

private T world;

public(T world) {
this.world = world;
}

T get() {
return world;
}
}
Is there any way to fetch the generic info on T, i.e. it has to be an object that extends World. I've tried this for a while, but it's really hard to find any information on this, as searching this on the internet only gives me the good old "how do I find the generic class on runtime" I only need generic info, and it does not need to be runtime. (I'm trying generate code out of code)
14 Replies
JavaBot
JavaBot2w ago
This post has been reserved for your question.
Hey @Thorinwasher! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.
TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.
dan1st
dan1st2w ago
You can use HelloWorld.class.getTypeParameters() to get the T
Thorinwasher
ThorinwasherOP2w ago
Oh... it's that easy...
dan1st
dan1st2w ago
Similarly, you an use Field#getGenericType For Method, there's getGenericReturnType() and getGenericParameterTypes() (and also getGenericExceptionTypes()) also Method#getTypeParameters if you have generic types declared in the method signature
Thorinwasher
ThorinwasherOP2w ago
Wow, thanks. I feel stupid now. It's literally been right there all the time 🤦‍♂️
JavaBot
JavaBot2w ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
dan1st
dan1st2w ago
finding stuff can be hard if you haven't seen it before
Thorinwasher
ThorinwasherOP2w ago
That's very true, I will try and use these and if it works, I will close this.
nikcho-kouhai
nikcho-kouhai2w ago
welcome to the world of type erasure. If you wanna submit a complaint get in line.
dan1st
dan1st2w ago
Why? What they want to do seems perfectly doable
nikcho-kouhai
nikcho-kouhai2w ago
it is, but you have to do it during runtime
Thorinwasher
ThorinwasherOP2w ago
Seems like this has solved my issue on that, so I will close this thread (Some other issue has surfaced now though which I have not thought about 😿 ) Thanks for the help by the way!
JavaBot
JavaBot2w ago
If you are finished with your post, please close it. If you are not, please ignore this message. Note that you will not be able to send further messages here after this post have been closed but you will be able to create new posts.
JavaBot
JavaBot2w ago
Post Closed
This post has been closed by <@270177852157067264>.

Did you find this page helpful?