www.fatihkabakci.com

Personal Website and Computer Science TUR EN

JAVA REFLECTION(YANSIMA)

Last update: 12/30/2014 9:24:00 PM

Yazan:Fatih KABAKCI

Reflection(Yansıma), Java Sanal Makinesinde(Java Virtual Machine, JVM) çalışan uygulamaların, çalışma zamanındaki(runtime) davranışlarını inceleme ve bu davranışlara yön verme imkanı sağlayan bir özelliktir. java.lang.reflect API' sinde tanımlanan yansıma özelliği, hata ayıklama(debugging) ve test araçlarında, görsel yazılım geliştirme ortamlarında kullanılmaktadır.

Konuyu bir örnek ile anlamaya çalışalım. Aşağıda Reflection adında bir sınıf bulunmaktadır. Bu sınıf klasik bir OOP(Object Oriented Programming - Nesne Yönelimli Programlama) sınıfı olarak içerisindeki 3 bilgiyi enkapsüle(encapsulation) etmektedir.

package com.fatihkabakci.Reflection;

/**
 * @author www.fatihkabakci.com
 */

public class Reflection {

   public final static int NO = 1;
   private String          name;
   private int             age;

   public Reflection() {
      this("John", 30);
   }

   public Reflection(String name, int age) {
      this.name = name;
      this.age = age;
   }

   public String getName() {
      return name;
   }

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

   public int getAge() {
      return age;
   }

   public void setAge(int age) {
      this.age = age;
   }

   public static void printNo() {
      System.out.println("No:" + NO);
   }

   public String toString() {
      return name + "," + age;
   }
   
   private void incrementAge() {
      ++age;
   }
}

Yukarıdaki bu sınıfı java.lang.reflect API yardımıyla çalışma zamanında inceleyelim. ReflectionApp isimli bu sınıf da aşağıda verilmektedir.

package com.fatihkabakci.Reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import java.lang.reflect.Field;

/**
 * @author www.fatihkabakci.com 
 * This class shows that how reflection is used
 * 
 * */

public class ReflectionApp {

   public static void main(String[] args) {

      try {
         Class<?> cls = Class.forName("com.fatihkabakci.Reflection.Reflection");
         Object obj = cls.newInstance();
         Constructor<?> cons = cls.getDeclaredConstructor(String.class, Integer.TYPE);
         for (Field field : cls.getDeclaredFields()) {
            System.out.println("Field:" + field.getName());
         }
         System.out.println();
         
         System.out.println("Modifiers:" + cons.getModifiers());
         System.out.println("Name:" + cons.getName());
         System.out.println("IsAccessible:" + cons.isAccessible());
         System.out.println("IsSynthetic:" + cons.isSynthetic());
         System.out.println("IsVarArgs:" + cons.isVarArgs());
         
         System.out.println();

         Method setAge = cls.getMethod("setAge", Integer.TYPE);
         setAge.invoke(obj, 25);
         
         Method getAge = cls.getMethod("getAge");
         Object age = getAge.invoke(obj);
         System.out.println("age:" + age);

         Method printNo = cls.getMethod("printNo");
         // calling static method with null object
         printNo.invoke(null);
         
         // getting the all methods include private with declared methods
         Method incrementAge = cls.getDeclaredMethod("incrementAge");
         // accessing to a private method
         incrementAge.setAccessible(true);
         incrementAge.invoke(obj);
         
         Method toString = cls.getMethod("toString");
         Object data = toString.invoke(obj);
         System.out.println("Person:" + data);
      }
      catch (ClassNotFoundException e) {
         System.err.print("The class not found: ");
         System.err.println(e.getMessage());
      }
      catch (InstantiationException e) {
         System.err.print("The object can not be instantiated from the class: ");
         System.err.println(e.getMessage());
      }
      catch (IllegalAccessException e) {
         System.err.print("illegal access to method");
         System.err.println(e.getMessage());
      }
      catch (NoSuchMethodException e) {
         System.err.print("No Such Method as ");
         System.err.println(e.getMessage());
      }
      catch (IllegalArgumentException e) {
         System.err.print("an illegal argument passing the method ");
         System.err.println(e.getMessage());
      }
      catch (InvocationTargetException e) {
         System.err.print("an invocation error ");
         System.err.println(e.getMessage());
      }
   }
}

Programın çıktısı aşağıda verilmektedir.

Field:NO
Field:name
Field:age

Modifiers:1
Name:com.fatihkabakci.Reflection.Reflection
IsAccessible:false
IsSynthetic:false
IsVarArgs:false

age:25
No:1
Person:John,26

Yukarıdaki sınıfta ilk olarak Reflection sınıfı forName oluşturulmaktadır. Ardından bu sınıftan bir instance oluşturulmaktadır. Burada oluşturulan nesne, çalışma zamanında parametresiz kurucu metot olan Reflection()' ı çağırır. getDeclaredConstructor() metotu sayesinde tanımlanmış kurucu metot elde edilir. Yansıma API' sinde Declared kelimesi, sınıfta tanımlanan private ya da public farketmeden her metot ya da üyeleri elde edeceğini söyler. Normal get metotlarından farkı budur. Normal get metotları private üyeleri elde edemez.

Nesne oluşturulduktan sonra, parametre verilerek sırasıyla kurucu metoduna ve üye alanlarına erişilmektedir. Burada sırasıyla, tanımlayıcısı(public, private, static, final), ismi, erişilebilir olması(public, private), sentetik olması(varsayılan başka bir kurucu metodu çağırıyor olması), parametre zinciri oluşturup oluşturmaması gibi bilgileri ekranda basılır. Daha sonra setAge() metodu invoke() sayesinde çalışma zamanında analiz edilerek çağrılır ve age değeri 25' e setlenir. Ardından getAge() metodu yine yansıma özelliği ile çağrılarak ekranda verify edilir.

Öte yandan static bir metot olan printNo() metodu ise, invoke(null) çağrısıyla çalıştırılır. Bunun anlamı, statik metotların çağrılırken bir nesneye ihtiyaç duymamasından kaynaklıdır. Ayrıca private bir metot olan incrementAge() metoduna erişim setAccessible(true) çağrısıyla aşılır. Tüm bu işlemler, yansımanın çalışma zamanında bir sınıfın özelliklerini değiştirebildiği anlamına da gelir.

Özetle reflection(yansıma), önemli bir özelliktir ve uygulamalarda kullanılması, çalışma zamanında sınıf özelliklerinin bilinmesi açısından yarar sağlar. Ancak bu API gerektiğinde kullanılmalıdır. Aksi halde, gereksiz sık kullanımlar sonucunda, çalışma zamanı tip bilgisi analizi, performans problemlerine, çalışma zamanında güvenlik izni gerektirmesi, sınırlı güvenlik ihlallerine, kodun private data erişimi gibi bir takım işlemlere maruz kalarak, beklenmedik yan etkilere yol açabilir.

MemberCommentDate:
guest
Başarılı

Güven

6/8/2020 2:33:00 AM

Name:


Question/Comment
   Please verify the image




The Topics in Computer Science

Search this site for





 

Software & Algorithms

icon

In mathematics and computer science, an algorithm is a step-by-step procedure for calculations. Algorithms are used for calculation, data processing, and automated reasoning.

Programming Languages

icon

A programming language is a formal constructed language designed to communicate instructions to a machine, particularly a computer. It can be used to create programs to control the behavior of a machine. Java,C, C++,C#

Database

icon

A database is an organized collection of data. The data are typically organized to model aspects of reality in a way that supports processes requiring information.

Hardware

icon

Computer hardware is the collection of physical elements that constitutes a computer system. Computer hardware refers to the physical parts or components of a computer such as the monitor, memory, cpu.

Web Technologies

icon

Web development is a broad term for the work involved in developing a web site for the Internet or an intranet. Html,Css,JavaScript,ASP.Net,PHP are one of the most popular technologies. J2EE,Spring Boot, Servlet, JSP,JSF, ASP

Mobile Technologies

icon

Mobile application development is the process by which application software is developed for low-power handheld devices, such as personal digital assistants, enterprise digital assistants or mobile phones. J2ME

Network

icon

A computer network or data network is a telecommunications network that allows computers to exchange data. In computer networks, networked computing devices pass data to each other along data connections.

Operating Systems

icon

An operating system is software that manages computer hardware and software resources and provides common services for computer programs. The OS is an essential component of the system software in a computer system. Linux,Windows

Computer Science

icon

Computer science is the scientific and practical approach to computation and its applications.A computer scientist specializes in the theory of computation and the design of computational systems.