You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

WriteExecutor.java 2.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package com.uqac.rthoni.java_rmi.server.executors;
  2. import com.uqac.rthoni.java_rmi.common.Command;
  3. import com.uqac.rthoni.java_rmi.server.ServerApplication;
  4. import java.lang.reflect.Field;
  5. import java.lang.reflect.Method;
  6. /**
  7. * Created by robin on 9/16/16.
  8. */
  9. public class WriteExecutor extends AbstractCommandExecutor {
  10. @Override
  11. public String getCommandName() {
  12. return "ecriture";
  13. }
  14. @Override
  15. public String run(Command command, ServerApplication server) throws Exception {
  16. String id = command.getArgument(0);
  17. String fieldName = command.getArgument(1);
  18. String methodName = String.format("set%s%s", fieldName.substring(0, 1).toUpperCase(), fieldName.substring(1));
  19. String value = command.getArgument(2);
  20. Object obj = server.getObject(id);
  21. Class objClass = obj.getClass();
  22. Field field = objClass.getDeclaredField(fieldName);
  23. try {
  24. field.set(obj, value);
  25. } catch (IllegalAccessException e) {
  26. try {
  27. Method method = objClass.getDeclaredMethod(methodName, String.class);
  28. method.invoke(obj, value);
  29. }
  30. catch (NoSuchMethodException e2) {
  31. try {
  32. Method method = objClass.getDeclaredMethod(methodName, int.class);
  33. method.invoke(obj, Integer.parseInt(value));
  34. }
  35. catch (NoSuchMethodException e3) {
  36. try {
  37. Method method = objClass.getDeclaredMethod(methodName, float.class);
  38. method.invoke(obj, Float.parseFloat(value));
  39. }
  40. catch (NoSuchMethodException e4) {
  41. try {
  42. Method method = objClass.getDeclaredMethod(methodName, boolean.class);
  43. method.invoke(obj, Boolean.parseBoolean(value));
  44. }
  45. catch (NoSuchMethodException e5) {
  46. throw new Exception("No such setter");
  47. }
  48. }
  49. }
  50. }
  51. }
  52. return null;
  53. }
  54. }