0

If I have a class Person.

public class Person{
  private String firstName;
  private String familyName;

  public String getFullName(){
    return firstName + " " + familyName;
  }
  public void setFullName(String name){
    String[] nameSplits = name.split(" ");
    this.firstName = nameSplits[0];
    this.familyName = nameSplits[1];
  }
}

Can i write person.fullName in java source code,and actual use person.getFullName()?

Also write person.fullName = "Angola Sim" while actual use person.setName("Angola Sim").

Is there any solution?

Yeezh
  • 141
  • 1
  • 7

2 Answers2

1

Solution in java for your statement is somehow possible by using reflection Example: Directly you can set the property of your setters without making setters

public static boolean set(Object object, String fieldName, Object fieldValue) {
    Class<?> clazz = object.getClass();
    while (clazz != null) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            field.set(object, fieldValue);
            return true;
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return false;
}

Call:

Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
set(instance, "firstName", "Shadab");
set(instance, "lastname", "siddiqui"

);

FYI, just make one equivalent generic getters method in your bean object, after doing operation whatever you want and return that field from that method

@SuppressWarnings("unchecked")
public static <V> V get(Object object, String fieldName) {
    Class<?> clazz = object.getClass();
    while (clazz != null) {
        try {
            Field field = clazz.getDeclaredField(fieldName);
            field.setAccessible(true);
            return (V) field.get(object);
        } catch (NoSuchFieldException e) {
            clazz = clazz.getSuperclass();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
    }
    return null;
}

Call:

Class<?> clazz = Class.forName(className);
Object instance = clazz.newInstance();
String name = get(instance, "Name");

And for boiler plate Yes there is one api called as Lombok just by using @data annotation you can make it, just add jar dependency in you maven and test this

Below is the jar dependency :

<dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <version>1.16.16</version>
        <scope>provided</scope>
    </dependency>

Lombok is used to reduce boilerplate code for model/data objects, e.g., it can generate getters and setters for those object automatically by using Lombok annotations. The easiest way is to use the @Data annotation.

import lombok.Data;

    @Entity
    @Data
    public class Todo {
        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Long id;
        private String star;
        private String desc;
    }

By simply adding the @data annotation you get all this for free: check out this link for more details on lombok https://projectlombok.org/features/GetterSetter

  • I had aleady used lombok in my project.Lombok can auto generate getter and setter when source code compile,we can save the time of declaring getter setter method,but still need use object.getField() in source code. – Yeezh Jul 22 '18 at 09:15
  • I even had given example of reflection, using that you can set your field dynamically without making setters.. Just by declaring getters you can achieve this functionality, let me know if I am clear with the question. – Shadab Siddiqui Jul 22 '18 at 09:17
  • reflection can do this,but it is not seems a good solution,because reflection has a bad performance at runtime,and will lose Static check by IDE and compiler. – Yeezh Jul 22 '18 at 09:19
  • Yeah I know, this I'll matters with performance little, but there is no other way to achieve this, just by reflection you can do this. This why they made reflection.. As per my understanding. – Shadab Siddiqui Jul 22 '18 at 09:20
  • You can check java.bean.Statment, may that helps you. – Shadab Siddiqui Jul 22 '18 at 09:21
  • https://stackoverflow.com/questions/5856895/java-reflection-beans-property-api check this out otherwise – Shadab Siddiqui Jul 22 '18 at 09:29
  • Ok,thank you.I want to find some plugin can make the getter invoked by changing the compiled byte code,just like lombok adding getter and setter method.If there is no way to achieve this,I would continue use getter directly – Yeezh Jul 22 '18 at 09:40
  • https://stackoverflow.com/questions/5178391/create-simple-pojo-classes-bytecode-at-runtime-dynamically check this out I feel that internally all of this using reflection, if there is no hard and fast thing and not making you stuck somewhere then you should use simple setters getters only. If there is some requirement you have to do this then only go with this things. – Shadab Siddiqui Jul 22 '18 at 09:53
0

You can annotate any field with @Getter and/or @Setter, to let lombok generate the default getter/setter automatically.

 import lombok.AccessLevel;
    import lombok.Getter;
    import lombok.Setter;

    public class GetterSetterExample {
      /**
       * Age of the person. Water is wet.
       * 
       * @param age New value for this person's age. Sky is blue.
       * @return The current value of this person's age. Circles are round.
       */
      @Getter @Setter private int age = 10;

      /**
       * Name of the person.
       * -- SETTER --
       * Changes the name of this person.
       * 
       * @param name The new value.
       */
      @Setter(AccessLevel.PROTECTED) private String name;

      @Override public String toString() {
        return String.format("%s (age: %d)", name, age);
      }
    }
Tejal
  • 764
  • 1
  • 10
  • 39