Loading...

Във форума е въведено ограничение, което позволява на потребителите единствено да разглеждат публикуваните въпроси.

kalin77 avatar kalin77 1 Точки

Lab: Reflection and Annotations -> 2.Getters and Setters

Здравейте колеги, може ли някой да сподели решение на задачата, защото вече не знам какво повече да опитам.

Условие:

2. Getters and Setters

Use reflection to get all Reflection methods. Then prepare an algorithm that will recognize, which methods are getters and setters. Sort each collection alphabetically by methods names. Print to console each getter on a new line in the format:

      • "{name} will return class {Return Type}"

Then print all setters in the format:

      • "{name} and will set field of class {Parameter Type}"

Do this without changing anything in "Reflection.java" 

 

Моето решение: pastebin.com/LND1RWgq

Judge: Reflection - Lab - SoftUni Judge

Благодаря предварително!

Тагове:
0
Java OOP Basics 10/01/2023 12:53:09
Axiomatik avatar Axiomatik 2422 Точки

Code by @KeepCoding, hope it helps =>

Main.java:

package p02_gettersAndSetters;

import java.lang.reflect.Method;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        Method[] allClassMethods = Reflection.class.getDeclaredMethods();

        Method[] getters = Arrays.stream(allClassMethods)
                .filter(m -> m.getName().startsWith("get"))
                .sorted((m1, m2) -> {
                    return m1.getName().compareTo(m2.getName());
                })
                .toArray(n -> new Method[n]);

        Method[] setters = Arrays.stream(allClassMethods)
                .filter(m -> m.getName().startsWith("set"))
                .sorted((m1, m2) -> {
                    return m1.getName().compareTo(m2.getName());
                })
                .toArray(n -> new Method[n]);

        for (int i = 0; i < getters.length; i++) {
            System.out.printf("%s will return %s%n", getters[i].getName(), getters[i].getReturnType()); //.getSimpleName() would look better, but judge doesn't like it
        }

        for (int i = 0; i < setters.length; i++) {
            System.out.printf("%s and will set field of %s%n", setters[i].getName(), setters[i].getParameters()[0].getType());
        }
    }
}

Reflection.java:

package p02_gettersAndSetters;

import java.io.Serializable;

public class Reflection implements Serializable {

    private static final String nickName = "Pinguin";
    public String name;
    protected String webAddress;
    String email;
    private int zip;

    public Reflection() {
        this.setName("Java");
        this.setWebAddress("oracle.com");
        this.setEmail("mail@oracle.com");
        this.setZip(1407);
    }

    private Reflection(String name, String webAddress, String email) {
        this.setName(name);
        this.setWebAddress(webAddress);
        this.setEmail(email);
        this.setZip(2300);
    }

    protected Reflection(String name, String webAddress, String email, int zip) {
        this.setName(name);
        this.setWebAddress(webAddress);
        this.setEmail(email);
        this.setZip(2300);
    }

    public final String getName() {
        return name;
    }

    private void setName(String name) {
        this.name = name;
    }

    protected String getWebAddress() {
        return webAddress;
    }

    private void setWebAddress(String webAddress) {
        this.webAddress = webAddress;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    protected final int getZip() {
        return zip;
    }

    private void setZip(int zip) {
        this.zip = zip;
    }

    public String toString() {
        String result = "Name: " + getName() + "\n";
        result += "WebAddress: " + getWebAddress() + "\n";
        result += "email: " + getEmail() + "\n";
        result += "zip: " + getZip() + "\n";
        return result;
    }
}

 

1
kalin77 avatar kalin77 1 Точки

Thank you for the fast response, but do you get 100/100 in judge? I tried your code and i found my mistakes, but still get 0 points in judge with both solutions. I start to think there is something wrong with judge.

0
Axiomatik avatar Axiomatik 2422 Точки

Sorry, didn't try it out. Assumed that it was correct - could be that there is an issue with judge if the exercise has been updated. Give it a shot with the following:

Main.java:

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

public class Main {
    public static void main(String[] args) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, IOException {

        Class ref = Reflection.class;

        System.out.println(ref);

        Class superClass = Reflection.class.getSuperclass();

        System.out.println(superClass);

        Class[] interfaces = ref.getInterfaces();

        Arrays.stream(interfaces).forEach(System.out::println);

        Object reflection = ref.getDeclaredConstructor().newInstance();

        System.out.println(reflection);

    }
}

GettersAndSetters.java:

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.Arrays;
import java.util.Comparator;

public class GettersAndSetters {
    public static void main(String[] args) {

        Class ref = Reflection.class;

        Method[] declaredMethods = ref.getDeclaredMethods();

        declaredMethods = Arrays.stream(declaredMethods).sorted(Comparator.comparing(Method::getName)).toArray(Method[]::new);

        for (Method declaredMethod : declaredMethods) {
            String name = declaredMethod.getName();

            if (name.contains("get")) {
                System.out.println(String.format("%s will return class %s", name, declaredMethod.getReturnType().getName()));
            }

        }
        for (Method declaredMethod : declaredMethods) {
            String name = declaredMethod.getName();

            if (name.contains("set")) {

                System.out.print(String.format("%s and will set field of class ", name));

                Parameter[] parameterTypes = declaredMethod.getParameters();

                for (int i = 0; i < parameterTypes.length; i++) {
                    System.out.print(parameterTypes[i].getType().getName() + " ");
                }
                System.out.println();
            }

        }
    }
}

Reflection.java:

import java.io.Serializable;

public class Reflection implements Serializable {

    private static final String nickName = "Pinguin";
    public String name;
    protected String webAddress;
    String email;
    private int zip;

    public Reflection() {
        this.setName("Java");
        this.setWebAddress("oracle.com");
        this.setEmail("mail@oracle.com");
        this.setZip(1407);
    }

    private Reflection(String name, String webAddress, String email) {
        this.setName(name);
        this.setWebAddress(webAddress);
        this.setEmail(email);
        this.setZip(2300);
    }

    protected Reflection(String name, String webAddress, String email, int zip) {
        this.setName(name);
        this.setWebAddress(webAddress);
        this.setEmail(email);
        this.setZip(2300);
    }

    public final String getName() {
        return name;
    }

    private void setName(String name) {
        this.name = name;
    }

    protected String getWebAddress() {
        return webAddress;
    }

    private void setWebAddress(String webAddress) {
        this.webAddress = webAddress;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    protected final int getZip() {
        return zip;
    }

    private void setZip(int zip) {
        this.zip = zip;
    }

    public String toString() {
        String result = "Name: " + getName() + "\n";
        result += "WebAddress: " + getWebAddress() + "\n";
        result += "email: " + getEmail() + "\n";
        result += "zip: " + getZip() + "\n";
        return result;
    }
}

 

0
10/01/2023 17:58:15
kalin77 avatar kalin77 1 Точки

It worked! Thank you again!

1
Можем ли да използваме бисквитки?
Ние използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Можете да се съгласите с всички или част от тях.
Назад
Функционални
Използваме бисквитки и подобни технологии, за да предоставим нашите услуги. Използваме „сесийни“ бисквитки, за да Ви идентифицираме временно. Те се пазят само по време на активната употреба на услугите ни. След излизане от приложението, затваряне на браузъра или мобилното устройство, данните се трият. Използваме бисквитки, за да предоставим опцията „Запомни Ме“, която Ви позволява да използвате нашите услуги без да предоставяте потребителско име и парола. Допълнително е възможно да използваме бисквитки за да съхраняваме различни малки настройки, като избор на езика, позиции на менюта и персонализирано съдържание. Използваме бисквитки и за измерване на маркетинговите ни усилия.
Рекламни
Използваме бисквитки, за да измерваме маркетинг ефективността ни, броене на посещения, както и за проследяването дали дадено електронно писмо е било отворено.