0

Let's say that I have defined these variables

RDFNode bd= soln.get(SparqlConstants.BD) ;
RDFNode alias = soln.get(SparqlConstants.ALIAS) ;
RDFNode thumbnail = soln.get(SparqlConstants.THUMBNAIL) ;
RDFNode battingSide = soln.get(SparqlConstants.BATTING_SIDE) ;

And then for each one of them, I have to set in a value in a setter method like this

if (bd!= null)
   player.setBirthDate(bd.asNode().getIndexingValue().toString());

Is there a way to have a generic method, that I pass the value and the method to call so generically this could be done in Java?

Mohamed Taher Alrefaie
  • 14,080
  • 5
  • 41
  • 62

5 Answers5

0

You can create a method and reuse it :

public String getIndexingValue(RDFNode node)
{
   return node.asNode().getIndexingValue().toString();
}

if(bd != null)
  player.setBirthDate(getIndexingValue(bd));
... and so on ...
Abubakkar
  • 14,610
  • 6
  • 50
  • 78
0

The only way to access/invoke a class/method based on textual name is through reflection. However, if your POJO adheres to the Java bean standard of getter/setter names, there are libraries, such as Apache Commons Beanutils that can hide away the reflection implementation.

Sharon Ben Asher
  • 12,476
  • 5
  • 25
  • 42
0

With reflection you can do this:

public void set(RDFNode node, String propertyName) {

    String methodName = "set" + propertyName; // <-- propertyName must be in upper CamelCase

    String value = node.asNode().getIndexingValue().toString();

    Method setMethod = player.getClass().getMethod(methodName, String.class);
    setMethod.invoke(player, value);
}
Héctor
  • 19,875
  • 26
  • 98
  • 200
  • 1
    `String methodName = "set" + propertyName;` will not work even if name is in camel case - you have to capitalize the name. but Apache bean utils takes care of that – Sharon Ben Asher Nov 03 '15 at 12:35
0

You could define a generic method on the player object and set the values using reflection.

public void setGenericValue(methodName, param) {
   this.getClass().getMethod(methodName, ...
}

Examples in this stackoverflow post: How do I invoke a Java method when given the method name as a string?

Community
  • 1
  • 1
Fraction
  • 443
  • 2
  • 11
0

You can use a method as -

private void setBirthDate(Player player, RDFNode obj) {
        if (obj != null) {
               player.setBirthDate(obj.asNode().getIndexingValue().toString());
        }
    }

And then call it like -

RDFNode bd= soln.get(SparqlConstants.BD);
setBirthDate(player, bd);
Saurabh
  • 2,055
  • 4
  • 32
  • 43