-
Notifications
You must be signed in to change notification settings - Fork 0
all in one #4
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
all in one #4
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| { | ||
| "configurations": [ | ||
|
|
||
| { | ||
| "type": "java", | ||
| "name": "CodeLens (Launch) - Launch", | ||
| "request": "launch", | ||
| "mainClass": "com.atumra.Launch", | ||
| "projectName": "hw05-proxy" | ||
| } | ||
| ] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| plugins { | ||
| // Apply the java plugin to add support for Java | ||
| //id 'java' | ||
| id 'java-library' | ||
| id 'com.github.johnrengelman.shadow' | ||
| } | ||
|
|
||
| sourceCompatibility = 11 | ||
| targetCompatibility = 11 | ||
|
|
||
| dependencies { | ||
| // This dependency is used by the application. | ||
| implementation 'com.google.guava:guava' | ||
| } | ||
|
|
||
| sourceSets.main.java.srcDirs = ['src/main/java'] | ||
|
|
||
| shadowJar { | ||
| archiveBaseName.set('hw05ProxyReal') | ||
| archiveVersion.set('0.1') | ||
| archiveClassifier.set('') | ||
| manifest { | ||
| attributes 'Main-Class': 'com.atumra.Launch' | ||
| } | ||
| } | ||
|
|
||
| tasks.build.dependsOn tasks.shadowJar |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| package com.atumra; | ||
|
|
||
| public class Calculator implements CalculatorLogging{ | ||
|
|
||
| @Override | ||
| public void calculate(int param) {}; | ||
|
|
||
| @Override | ||
| public void calculate(int param1, int param2) {}; | ||
|
|
||
| public void calculateA(int param1, int param2) {}; | ||
|
|
||
| @Log | ||
| @Override | ||
| public void calculate(int param1, int param2, String param3) {}; | ||
| } |
12 changes: 12 additions & 0 deletions
12
hw05-proxy/src/main/java/com/atumra/CalculatorLogging.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.atumra; | ||
|
|
||
| public interface CalculatorLogging { | ||
|
|
||
| @Log | ||
| public void calculate(int param); | ||
|
|
||
| public void calculate(int param1, int param2); | ||
|
|
||
| public void calculate(int param1, int param2, String param3); | ||
|
|
||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,50 @@ | ||
| package com.atumra; | ||
|
|
||
| import java.lang.reflect.InvocationHandler; | ||
| import java.lang.reflect.Method; | ||
| import java.lang.reflect.Proxy; | ||
| import java.util.Arrays; | ||
| import java.util.Set; | ||
| import java.util.stream.Collectors; | ||
|
|
||
|
|
||
| public class Ioc { | ||
|
|
||
| private Ioc() { | ||
| } | ||
|
|
||
| static CalculatorLogging createCalculator() { | ||
| InvocationHandler handler = new CalculatorInvocationHandler(new Calculator()); | ||
|
|
||
| return (CalculatorLogging) Proxy.newProxyInstance( | ||
| Ioc.class.getClassLoader(), | ||
| // interface, which class implements | ||
| new Class<?>[]{CalculatorLogging.class}, | ||
| handler); | ||
| } | ||
|
|
||
| static class CalculatorInvocationHandler implements InvocationHandler { | ||
| private final CalculatorLogging myClass; | ||
| private Set<Object> annotatedParamCounts; | ||
|
|
||
| CalculatorInvocationHandler(CalculatorLogging myClass) throws IllegalArgumentException { | ||
| this.myClass = myClass; | ||
| Class<?> cl= myClass.getClass(); | ||
|
|
||
| annotatedParamCounts = Arrays.stream(cl.getMethods()) | ||
| .filter(method -> method.isAnnotationPresent(Log.class)) | ||
| .map(method -> String.valueOf(method.getParameterCount())+method.getName()+ Arrays.toString(method.getParameterTypes())) | ||
| .collect(Collectors.toSet()); | ||
| } | ||
|
|
||
| // В консоли дожно быть: executed method: calculation, param: 6 | ||
| public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { | ||
| // System.out.println(method + " annotation" + method.isAnnotationPresent(Log.class)); | ||
|
|
||
| if (annotatedParamCounts.contains(String.valueOf(method.getParameterCount())+method.getName()+Arrays.toString(method.getParameterTypes())) ) | ||
| System.out.println("executed method:" + method.getName() + ", param: " + Arrays.toString(args)); | ||
| return method.invoke(myClass, args); | ||
| } | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,15 @@ | ||
| package com.atumra; | ||
|
|
||
| public class Launch { | ||
| public static void main(String[] args) { | ||
| CalculatorLogging myClass = Ioc.createCalculator(); | ||
| System.out.println("one arg"); | ||
| myClass.calculate(3); | ||
| System.out.println("two args not logged"); | ||
| myClass.calculate(3, 3); | ||
| System.out.println("three args"); | ||
| myClass.calculate(3, 3, "sum"); | ||
| System.out.println("все"); | ||
| } | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,12 @@ | ||
| package com.atumra; | ||
|
|
||
| import java.lang.annotation.ElementType; | ||
| import java.lang.annotation.Retention; | ||
| import java.lang.annotation.RetentionPolicy; | ||
| import java.lang.annotation.Target; | ||
|
|
||
| @Retention(RetentionPolicy.RUNTIME) | ||
| @Target(ElementType.METHOD) | ||
| public @interface Log { | ||
|
|
||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,29 @@ | ||
| Автоматическое логирование. | ||
|
|
||
| Цель: | ||
| Понять как реализуется AOP, какие для этого есть технические средства. | ||
|
|
||
| Разработайте такой функционал: метод класса можно пометить самодельной аннотацией @Log, например, так: | ||
|
|
||
| class TestLogging { | ||
| @Log | ||
| public void calculation(int param) {}; } | ||
|
|
||
| При вызове этого метода "автомагически" в консоль должны логироваться значения параметров. Например так. | ||
|
|
||
| class Demo { | ||
| public void action() { | ||
| new TestLogging().calculation(6); | ||
| } | ||
| } | ||
|
|
||
| В консоле дожно быть: executed method: calculation, param: 6 | ||
|
|
||
| Обратите внимание: явного вызова логирования быть не должно. | ||
|
|
||
| Учтите, что аннотацию можно поставить, например, на такие методы: | ||
| public void calculation(int param1) | ||
| public void calculation(int param1, int param2) | ||
| public void calculation(int param1, int param2, String param3) | ||
|
|
||
| P.S. Выбирайте реализацию с ASM, если действительно этого хотите и уверены в своих силах. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,2 +1,2 @@ | ||
| rootProject.name = 'java.practice' | ||
| include 'hw03-reflection' | ||
| include 'hw05-proxy' |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
аннотация должне стоять на методах класса, а не интерфейса
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Сергей добрый день, Я общался с Виталием Куценко в слаке по этому вопросу ()кстати по его пожеланию Слак - мне Слак крайне не удобен.)

There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ида вы правы сделано это было так потому что я не мсог найте нормального подхода и написал ему - ответа я не получил. делать как не знаю... Сделал как смог
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Вам надо понять, методы какого класса выполняются, и именно на нем искать аннотации.
Это можно сделать в конструкторе:
результаты сохранить и в public Object invoke(Object proxy, Method method, Object[] args)
к ним обратиться.
Т.е. надо разбрать методы myClass и найти, те, где есть аннотация.
При обработке invoke надо проверить, что вызывается метод с аннотацией.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ответил в чате для задания