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

139
Visualizações
Passing Object Type into method as a Parameter?

I have the following method that returns a Person object by Id:

   private Person getPersonById(String client) {

    Person output = null;
    EntityManager entityManager = null;

    try {
        entityManager = entityManagement.createEntityManager(client);
        output = entityManager.find(Person.class, id);

    } catch (Exception e) {
     
     // handle
    
    } finally {
        entityManagement.closeEntityManager(client, entityManager);
    }
    return output;
}

Is there a way I can make this method more generic so that I can pass in other object types, e.g. Place , Cost as well? Note that these do not inherit the same super class.

E.g. should I pass e.g. Person.class as a method parameter etc?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If you want to pass in a class object and make your method generic, you could do this:

private <E> E getObjectById(String client, Class<E> cls) {

    E output = null;
    EntityManager entityManager = null;

    try {
        entityManager = entityManagement.createEntityManager(client);
        output = entityManager.find(cls, id);

    } catch (Exception e) {
     
     // handle
    
    } finally {
        entityManagement.closeEntityManager(client, entityManager);
    }
    return output;
}

If you pass Person.class as the cls argument, it would be equivalent to your original code.

That's supposing that entityManager.find will accept any class and attempt to return an instance of that class.

If entityManager.find has some restriction on the characteristics of the class it accepts, you would need to specify them in your generic type parameter <E>.

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