Saturday, June 30, 2018

Extract Java class variables

I'm not a big fan of Java. I spent too many years with C++ and Java is not a revolution here. It's a solid and powerful language but I feel (like in C++) too close to machine. Sometimes it's good, but sometimes it's not. It was functional programming what changed my thinking about programming. Instead of managing memory cells I started thinking about defining functions and relations.

I like to solve non trivial problems and Scala seems to be perfect solution. But I found Java since version 8 very close to functional languages. Improvements to interfaces and lambdas allow us to make almost all the magic that we love in Scala (if you don't believe type 'functional Java' in Google).

Don't get me wrong: I'm not focused on any magic; Object Oriented Programming is from my point of view still the most important factor in any sophisticated system. It's OOP what helps to design a good architecture. But sometimes you need to join different systems. You need to deal with some new components and old legacy code. And Java brings here a lot of useful libraries.

Here's a useful snippet if you need to extract specific fields from class:


  class MyClass {
    private int iV1;
    private int iV2;
    private String sV1;
    private String sV2;

    MyClass(int v1, int v2, String sv1, String sv2) {
      iV1 = v1;      iV2 = v2;      sV1 = sv1;      sV2 = sv2;
    }
  }

  List<String> getStrings(MyClass cl) {
    return Arrays.stream(cl.getClass().getDeclaredFields()).
            filter(e -> String.class.isAssignableFrom(e.getType())).
            map(e -> {
              try {
                e.setAccessible(true);
                return (String)e.get(cl);
              } catch (Exception ex) {
                return "";
              }
            }).filter(s -> !s.isEmpty()).
            collect(Collectors.toList());
  }

  public void testFieldsExtractor() {
    getStrings(new MyClass(1, 2, "first", "second")).
            forEach(System.out::println);   // out: first, second
  }


No comments:

Post a Comment

Extract Java class variables

I'm not a big fan of Java. I spent too many years with C++ and Java is not a revolution here. It's a solid and powerful language but...