Home > OS >  How to access "types" dynamically with java?
How to access "types" dynamically with java?

Time:08-21

I don't know what types.DocumentType is, but I'm doing an integration of an sdk and I created a cordova plugin. the import from the sdk is like this:

import exemple.types.DocumentType;

example.open(DocumentType.RG_FRENTE, myListener);

Can I somehow pass RG_FRENTE dynamically as it is done in javascript?

Something like:

example.open(DocumentType[my_parameter], myListener);

CodePudding user response:

What @shmosel said is to define somewhere in your code a Map like:

Map<String,Integer> documentTypes = new HashMap<>() {{
                put("RG_FRENTE",DocumentType.RG_FRENTE);
                put("RG_ETNERF",DocumentType.RG_ETNERF);
        }};

(I assume here DocumentType.RG_FRENTE is an int (can be Object), as you don't tell us the type)

Later, you can access the values dynamically like

String my_parameter = "RG_FRENTE";
// ...
example.open(documentTypes.get(my_parameter), myListener);

If you like, you can create documentTypes by reflection, but always is better to avoid reflection in code.

CodePudding user response:

This solution is only if DocumentType is enum class like below.

enum DocumentType {
    RG_FRENTE,
    RG_ETNERF;
}

You can directly get by the valueOf method like below.

DocumentType docType = DocumentType.valueOf("RG_ETNERF");

Or like this, if you have it in variable.

String type = "RG_ETNERF";
DocumentType docType = DocumentType.valueOf(type);
  • Related