reflection

hyeonn's avatar
Jan 12, 2024
reflection
  • Reflection이 private 데이터에 접근할 수 있는 원리 → Java의 Reflection API가 접근 수준을 무시하는 일부 메커니즘을 제공하기 때문이다.
  • Reflection은 일종의 메타프로그래밍 기법 → 실행 중에 클래스의 구조를 조사하고 조작하는 기능을 제공하며 private 멤버에도 접근 가능
public class Post { private int userId; private int id; private String title; private String body; // 빈생성자 public Post(){ } public Post(int userId, int id, String title, String body) { this.userId = userId; this.id = id; this.title = title; this.body = body; } public int getUserId() { return userId; } public int getId() { return id; } public String getTitle() { return title; } public String getBody() { return body; } @Override public String toString() { return "Post{" + "userId=" + userId + ", id=" + id + ", title='" + title + '\'' + ", body=" + body + '}'; } }
빈생성자(디폴트 생성자)를 만들어야 자동으로 필드를 넣어서 출력해줌
import com.fasterxml.jackson.databind.ObjectMapper; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class MyApp2 { public static void main(String[] args) { try { URL url = new URL("https://jsonplaceholder.typicode.com/posts/1"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); BufferedReader br = new BufferedReader( new InputStreamReader(con.getInputStream()) ); String download = ""; while (true){ String line = br.readLine(); if (line == null) break; download = download + line; } ObjectMapper om = new ObjectMapper(); Post post = om.readValue(download, Post.class); System.out.println(post.toString()); } catch (Exception e) { throw new RuntimeException(e); } } }
 
{ "userId": 1, "id": 1, "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum" }
{ } → 중괄호는 JSON Object
Share article

from-web-developer