lundi 6 mars 2017

Java reflection errors with abstract class

Using the Java reflection to retrieve all fields value using the abstract class Poligono it creates to problems: the first is that getDeclaredFields() does return nothing (an array of 0 value instead of three fields inside the class) and field.get(object) raise an unreported exception IllegalAccessException

import java.lang.reflect.*;
import java.util.ArrayList;

abstract class Poligono
{
    int numVertici;
    double base;
    double altezza;

    int getNumeroVertici()
    {
        return numVertici;
    }

    abstract double getArea();
    abstract double getPerimetro();
}

class Triangolo extends Poligono
{
    public Triangolo(double lato)
    {
        numVertici = 3;
        base = lato;
    }

    public double getArea()
    {
        return ((base * base) / 4) * Math.sqrt(3);
    }

    public double getPerimetro()
    {
        return base * 3;
    }
}

class Rettangolo extends Poligono
{
    public Rettangolo(double base_p, double altezza_p)
    {
        numVertici = 4;
        base = base_p;
        altezza = altezza_p;
    }

    public double getArea()
    {
        return (base * altezza) / 2;
    }

    public double getPerimetro()
    {
        return 2 * (base + altezza);
    }
}

class Geometrie
{
    ArrayList<Poligono> lista;

    public Geometrie()
    {
        lista = new ArrayList<Poligono>();
    }

    public void aggiungi(Poligono p)
    {
        lista.add(p);
    }

    public int numeroPoligoni()
    {
        return lista.size();
    }

    public boolean checkPoligono(Poligono p)
    {
        for (Poligono q : lista)
        {
            if (q.getClass().equals(p.getClass()))
            {
                Field[] fields = p.getClass().getDeclaredFields();

                System.out.println(fields.length); // length is 1
                for (Field field : fields) {
                  field.setAccessible(true); //Additional line
                  System.out.println("Field Name: " + field.getName());
                  System.out.println("Field Type: " + field.getType());
                  System.out.println("Field Value: " + field.get(p)); // IllegalAccessException
                }
            }
        }
        return true;
    }
}

public class Main
{
    public static void main(String [] args)
    {
        Geometrie g = new Geometrie();
        Rettangolo r = new Rettangolo(2, 3);
        Rettangolo r2 = new Rettangolo(2, 3);

        g.aggiungi(r);
        g.checkPoligono(r2);
    }
}





Aucun commentaire:

Enregistrer un commentaire