Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

212
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda