Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Find the Class Reference Of Genric Type
@Service
public abstract class MainService<E extends AbstractEntity, R extends MainRepository<E>> {

    @Autowired
    MainRepository<E> repository;

    public E find(long id) throws Exception {
        return this.repository.find(---, id);
    }
}

Here is it possible to find the class reference of the generic type E to pass through this method as first argument instead of the --- ...?

My expectation about the implementation is to create a generic call to avoid the repetition of the below code in all service classes.

return this.repository.find(Entity.class,id);
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Yes, here's an example of doing that:

import java.lang.reflect.ParameterizedType;

public class Foo {
    public static abstract class Bar<E> {
        public E returnAnE() throws InstantiationException, IllegalAccessException {
            Class e = (Class)((ParameterizedType)this.getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            return (E)e.newInstance();
        }
    }

    public static class Baz extends Bar<String> {

    }

    public static void main(String[] args) throws InstantiationException, IllegalAccessException {
        Baz baz = new Baz();
        String s = baz.returnAnE();
    }
}

This code will fail with class structures which don't match what we have here, so you should do instance of checks instead of casts, and check array accesses.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!