Skip to content

Reflect hw2#5

Open
deadlovelll wants to merge 21 commits intomasterfrom
master
Open

Reflect hw2#5
deadlovelll wants to merge 21 commits intomasterfrom
master

Conversation

@deadlovelll
Copy link

No description provided.

constructor.setAccessible(true);
Object instance = constructor.newInstance(params);
return instance;
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

У нас в целом задача -- создание разнообразных объектов случайных. Как на счет идеи пройтись по полям и случайно их сгенерировать?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кажется сейчас я могу подать на вход любой класс какой хочу и ваш алгоритм попытается его обработать... Что будет если я подам не Generatable класс?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправил

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Можно не переделывать, но обратите внимание на Collection.class.isAssignableFrom (аналогично для Map). Упростит ли это как то задачу?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Спасибо. Все равно исправил, да упрощает, делает возможным не заходить в функцию генерации мапы/листа если обьект таковым не является

{
int randomSize = random.nextInt(100);
for (int i = 0; i < randomSize; i++) {
map.put(String.valueOf(i), new Object());
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

На самом деле таки есть способ получить типы из коллекций вроде есть.
Подсказка -- посмотрите на наследников Type, кажется там есть ParameterizedType
Если что, поресерчьте репы некоторых одногруппников. Эта штука не самая очевидная и распространенная

Просьба потом отписать, как оно устроено и почемы мы можем получить типы несмотря на стирание

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Да, это можно сделать, проблема в том что type erasure работает на уровне рантайма, но данные остаются в метаданных обьявления переменной. Но такое не будет работать для обьектов которые созданы прям совсем на лету

Я исправил код и попробовал сгенерировать класс с джеенрик типом, результат:

Generated org.example.classes.Cart@34a245ab
With attributes:
Field items with type:interface java.util.List and value:[org.example.classes.Product@12edcd21, org.example.classes.Product@34c45dca, org.example.classes.Product@52cc8049]

Все получилось

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Какая то странная проверка, напомните пж -- зачем она?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Изначально подумал что если класс в аттрибутах имеет обьекты своего же класса - то такие обьекты не стоит генерировать. Когда показывал лабу обсудили что лучше поставить лимит рекурсии

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Исправил. Теперь подобные обьекты могут создаваться, без возврата null

@deadlovelll
Copy link
Author

Добавил так же обсуждаемое поведение по интерфейсам - теперь если передается интерфейс то будет создаваться класс, который имплементирует его, а не возвращает null

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants

Comments