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

217
Visualizações
How to use Reflection in typescript similarly like in java?

I'm using reflection in Java to obtain some information from the TestNG annotation like in the code snippet below:

Reflections reflections = new Reflections("", new MethodAnnotationsScanner())
Set<Method> annotated = reflections.getMethodsAnnotatedWith(Test.class)

Currently, I have a jest framework with a jest-decorated plugin to help in using annotations.

How I can replicate the same reflection method in Java but in typescript to collect this information from the annotations?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Please take a look at Typescript's Decorators + Reflect Metadata API, which can also be enabled for TS compiler. It doesn't work exactly as Java, but you still can collect required information about annotated entities. Small example of how to collect annotated classes:

const myTypes: any[] = []

@annotation
class MyClass {
  type = "report";
  title: string;
 
  constructor(t: string) {
    this.title = t;
  }
}

function annotation(constructor: Function) {
    myTypes.push(constructor)
}

console.log('All annotated classes', myTypes);

about 4 years ago · Juan Pablo Isaza Relatório

0

Try tst-reflect. It is pretty advanced Reflection system for TypeScript (using custom typescript transformer plugin).

This should be equivalent of your Java code:

import {
    reflect,
    Type
} from "tst-reflect";

// Some decorator...
function test(_, __)
{
}

@reflect()
class A
{
    @test
    foo()
    {
        return 0;
    }

    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class B
{
    @test
    bar()
    {
        return "lorem ipsum";
    }
}

@reflect()
class C
{
    baz()
    {
        return "lorem ipsum";
    }
}

const decoratedMethods = Type.getTypes()
    .flatMap(type => type.getMethods().map(method => ({ method, type })))
    .filter(entry => entry.method.getDecorators().some(decorator => decorator.name == "test"));

for (let entry of decoratedMethods)
{
    console.log(entry.method.name, "in", entry.type.name);
}

Output

foo in A
bar in B

Check Synopsis. You are able to create instances of those types (even they are from different files) and call those methods. Also those decorators can have arguments so you will be able to filter methods with same decorators but different arguments.

tst-reflect is still in development so the global look ups of types require those @reflect decorators or custom decorators with @reflect JSDoc tag; reason is size optimization of the generated metadata. But there is an issue to extend configuration by "include" glob patterns which will include all types from all the modules matched by that globs.

PS: Check out configuration wiki and use this configuration:

tsconfig.json

{
    "compilerOptions": {
        // your options...

        // ADD THIS!
        "plugins": [
            {
                "transform": "tst-reflect-transformer"
            }
        ]
    },
    // ADD THIS!
    "reflection": {
        "metadata": {
            "type": "typelib" // this mode will generate and auto-import library with generated reflection metadata
        }
    }
}
about 4 years ago · Juan Pablo Isaza 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