How to acces annotation properties | Community
Skip to main content
Level 4
October 16, 2015
Solved

How to acces annotation properties

  • October 16, 2015
  • 3 replies
  • 1135 views

Hi,

I have a property like this:

@Property(name = "myvar", value = "myvalue")

I need to access this property inside the code.

I can do this with:

@Activate public void activate(ComponentContext ctx) { Dictionary dic = ctx.getProperties(); Enumeration keys = dic.keys(); List<String> list = Collections.list(keys); Collections.sort(list); for (String key : list) if (key.equals("myvar")) portal_server = String.valueOf(dic.get((Object) key)); }

Is there a simpler way?

Thanks

This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by joerghoh

Hi,

I use code like this:

@Activate protected void activate (ComponentContext ctx) { String myvar = PropertyUtils.toString (ctx.getProperties().get("myvar"), "defaultValue"); }

The PropertyUtils helper is very useful, as it provides many conversion tools including the support for a default value, if the property is not provided or empty.

3 replies

smacdonald2008
Level 10
October 16, 2015

Invoking the https://osgi.org/javadoc/r4v42/org/osgi/service/component/ComponentContext.html#getProperties() method is the supported way to dynamically determine properties values used within OSGi. 

Yogesh_Upadhyay
Level 6
October 16, 2015

You can also do something like

@Activate protected void activate(final Map<String, Object> config) { String myvar = PropertiesUtil.toString(config.get(PROP_NAME),DEFAULT_VALUE); }
joerghoh
Adobe Employee
joerghohAdobe EmployeeAccepted solution
Adobe Employee
October 16, 2015

Hi,

I use code like this:

@Activate protected void activate (ComponentContext ctx) { String myvar = PropertyUtils.toString (ctx.getProperties().get("myvar"), "defaultValue"); }

The PropertyUtils helper is very useful, as it provides many conversion tools including the support for a default value, if the property is not provided or empty.