mardi 29 mai 2018

How to instantiate dynamically interface, and use their methods?

I'm working on a simple 2D game in Java. There's 2 Robot: they can move, fight etc.. These classes implement same interface.

Questions are:

  1. How to instantiate Robots in run time? I mean, when the program is running, ask the user to load classes, after that use their methods (Press 1 to get your own shield points..) like a role playing games.. I tried to do with Reflection but it doesn't work on interface.

    My reflection method:

    public void invokeClassMethod(String classBinaryName, String methodName) {
    
        try {
            ClassLoader classLoader = this.getClass().getClassLoader();
            Class<?> loadClass = classLoader.loadClass(classBinaryName);
    
            System.out.println("Loaded class name: " + loadClass.getName());
    
            Constructor<?> constructor = loadClass.getConstructor();
            Object classObject = constructor.newInstance();
    
            Method method = loadClass.getMethod(methodName);
            System.out.println("Invoked method name: " + method.getName());
            method.invoke(classObject);
    
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    
  2. Is it a good way to get enemyPosition()?

Robot interface:

public interface Robot {

    public String getPosition();

    public String getEnemyPosition();

    public String getArenaSize();

    public int getShield();

}

Robot1 class:

public class Robot1 implements Robot {

    private int xCurrent;
    private int yCurrent;
    private int shield;
    private final int attack = 1;

    Robot robot2;

    public Robot1() {
    }

    public Robot1(int x, int y, int shield, Robot robot2) {
        this.xCurrent = x;
        this.yCurrent = y;
        this.shield = shield;
        this.robot2 = robot2;
    }

    @Override
    public String getPosition() {
        return "x: " + xCurrent + " y: " + yCurrent;
    }

    @Override
    public String getEnemyPosition() {
        return robot.getPosition();
    }

    @Override
    public int getShield() {
        return shield;
    }
}

  1. Furthermore the Arena class stores game board informations like arena size, printing etc... If I want to operate on this arena (moving Robot objects [1][1] ---> [3][2]) how to connect Robot interface and Arena with each other?

  2. Where to store their positions (in concrete class or somewhere else)? Is aggregation a best way?How to avoid tight coupling?





Aucun commentaire:

Enregistrer un commentaire