Bu eğiticide, sınıfları, yöntemleri vb. İncelememize ve değiştirmemize olanak tanıyan Java programlamada bir özellik olan yansımayı öğreneceğiz.
Java'da yansıma, çalışma zamanında sınıfları, arayüzleri, oluşturucuları, yöntemleri ve alanları incelememize ve değiştirmemize olanak tanır.
Java'da Class
, çalışma zamanında nesneler ve sınıflar hakkındaki tüm bilgileri tutan bir sınıf vardır . Class nesnesi yansıtma yapmak için kullanılabilir.
Java Sınıflarının Yansıması
Bir Java sınıfını yansıtmak için önce bir Class nesnesi oluşturmamız gerekir.
Ve nesneyi kullanarak, bir sınıfta bulunan yöntemler, alanlar ve yapıcılar hakkında bilgi almak için çeşitli yöntemler çağırabiliriz.
Sınıf nesnelerini oluşturmanın üç yolu vardır:
1. forName () yöntemini kullanma
class Dog (… ) // create object of Class // to reflect the Dog class Class a = Class.forName("Dog");
Burada forName()
yöntem, yansıtılacak sınıfın adını argüman olarak alır.
2. getClass () yöntemini kullanma
// create an object of Dog class Dog d1 = new Dog(); // create an object of Class // to reflect Dog Class b = d1.getClass();
Burada, bir Class nesnesi oluşturmak için Dog sınıfının nesnesini kullanıyoruz.
3. .class uzantısını kullanma
// create an object of Class // to reflect the Dog class Class c = Dog.class;
Artık Class
. Bu nesneyi çalışma zamanında ilgili sınıf hakkında bilgi almak için kullanabiliriz.
Örnek: Java Sınıfı Yansıması
import java.lang.Class; import java.lang.reflect.*; class Animal ( ) // put this class in different Dog.java file public class Dog extends Animal ( public void display() ( System.out.println("I am a dog."); ) ) // put this in Main.java file class Main ( public static void main(String() args) ( try ( // create an object of Dog Dog d1 = new Dog(); // create an object of Class // using getClass() Class obj = d1.getClass(); // get name of the class String name = obj.getName(); System.out.println("Name: " + name); // get the access modifier of the class int modifier = obj.getModifiers(); // convert the access modifier to string String mod = Modifier.toString(modifier); System.out.println("Modifier: " + mod); // get the superclass of Dog Class superClass = obj.getSuperclass(); System.out.println("Superclass: " + superClass.getName()); ) catch (Exception e) ( e.printStackTrace(); ) ) )
Çıktı
İsim: Köpek Düzenleyici: genel Süper Sınıf: Hayvan
Yukarıdaki örnekte, bir üst sınıf oluşturduk: Hayvan ve bir alt sınıf: Köpek. Burada Köpek sınıfını incelemeye çalışıyoruz.
İfadeye dikkat edin,
Class obj = d1.getClass();
Burada, getClass()
yöntemi kullanarak Class nesnesinin bir objesini oluşturuyoruz . Nesneyi kullanarak, farklı Class metodlarını çağırıyoruz.
- obj.getName () - sınıfın adını döndürür
- obj.getModifiers () - sınıfın erişim değiştiricisini döndürür
- obj.getSuperclass () - sınıfın süper sınıfını döndürür
Daha fazla bilgi edinmek için Class
Java Class'ı (resmi Java belgeleri) ziyaret edin.
Not : Modifier
Tamsayı erişim değiştiricisini bir dizeye dönüştürmek için sınıfı kullanıyoruz .
Alanları, Yöntemleri ve Yapıcıları Yansıtma
Paket java.lang.reflect
, sınıf üyelerini işlemek için kullanılabilecek sınıflar sağlar. Örneğin,
- Yöntem sınıfı - bir sınıftaki yöntemler hakkında bilgi sağlar
- Alan sınıfı - bir sınıftaki alanlar hakkında bilgi sağlar
- Yapıcı sınıfı - bir sınıftaki yapıcılar hakkında bilgi sağlar
1. Java Yöntemlerinin Yansıması
Method
Sınıf bir sınıfta yöntemler mevcut hakkında bilgi almak için kullanılabilecek çeşitli yöntemler sağlar. Örneğin,
import java.lang.Class; import java.lang.reflect.*; class Dog ( // methods of the class public void display() ( System.out.println("I am a dog."); ) private void makeSound() ( System.out.println("Bark Bark"); ) ) class Main ( public static void main(String() args) ( try ( // create an object of Dog Dog d1 = new Dog(); // create an object of Class // using getClass() Class obj = d1.getClass(); // using object of Class to // get all the declared methods of Dog Method() methods = obj.getDeclaredMethods(); // create an object of the Method class for (Method m : methods) ( // get names of methods System.out.println("Method Name: " + m.getName()); // get the access modifier of methods int modifier = m.getModifiers(); System.out.println("Modifier: " + Modifier.toString(modifier)); // get the return types of method System.out.println("Return Types: " + m.getReturnType()); System.out.println(" "); ) ) catch (Exception e) ( e.printStackTrace(); ) ) )
Çıktı
Yöntem Adı: display Değiştirici: public Dönüş Türleri: void Yöntem Adı: makeSound Değiştirici: private Dönüş Türleri: void
Yukarıdaki örnekte, Dog sınıfında bulunan yöntemler hakkında bilgi almaya çalışıyoruz. Daha önce de belirtildiği gibi, ilk önce yöntemi Class
kullanarak bir nesne objesi oluşturduk getClass()
.
İfadeye dikkat edin,
Method() methods = obj.getDeclaredMethod();
Burada, getDeclaredMethod()
sınıf içinde bulunan tüm yöntemleri döndürür.
Ayrıca, Method
sınıfın bir m nesnesini oluşturduk . Buraya,
- m.getName () - bir yöntemin adını döndürür
- m.getModifiers () - yöntemlerin erişim değiştiricisini tamsayı biçiminde döndürür
- m.getReturnType () - yöntemlerin dönüş türünü döndürür
Method
Sınıf da zamanında yöntemleri incelemek için kullanılabilecek çeşitli başka yöntemler de sağlar. Daha fazla bilgi edinmek için Java Yöntemi sınıfını (resmi Java belgeleri) ziyaret edin.
2. Java Alanlarının Yansıması
Yöntemler gibi, sınıfın yöntemlerini kullanarak bir sınıfın farklı alanlarını da inceleyebilir ve değiştirebiliriz Field
. Örneğin,
import java.lang.Class; import java.lang.reflect.*; class Dog ( public String type; ) class Main ( public static void main(String() args) ( try ( // create an object of Dog Dog d1 = new Dog(); // create an object of Class // using getClass() Class obj = d1.getClass(); // access and set the type field Field field1 = obj.getField("type"); field1.set(d1, "labrador"); // get the value of the field type String typeValue = (String) field1.get(d1); System.out.println("Value: " + typeValue); // get the access modifier of the field type int mod = field1.getModifiers(); // convert the modifier to String form String modifier1 = Modifier.toString(mod); System.out.println("Modifier: " + modifier1); System.out.println(" "); ) catch (Exception e) ( e.printStackTrace(); ) ) )
Çıktı
Değer: labrador Değiştirici: public
Yukarıdaki örnekte, Dog adında bir sınıf oluşturduk. Type adında bir genel alan içerir. İfadeye dikkat edin,
Field field1 = obj.getField("type");
Here, we are accessing the public field of the Dog class and assigning it to the object field1 of the Field class.
We then used various methods of the Field
class:
- field1.set() - sets the value of the field
- field1.get() - returns the value of field
- field1.getModifiers() - returns the value of the field in integer form
Similarly, we can also access and modify private fields as well. However, the reflection of private field is little bit different than the public field. For example,
import java.lang.Class; import java.lang.reflect.*; class Dog ( private String color; ) class Main ( public static void main(String() args) ( try ( // create an object of Dog Dog d1 = new Dog(); // create an object of Class // using getClass() Class obj = d1.getClass(); // access the private field color Field field1 = obj.getDeclaredField("color"); // allow modification of the private field field1.setAccessible(true); // set the value of color field1.set(d1, "brown"); // get the value of field color String colorValue = (String) field1.get(d1); System.out.println("Value: " + colorValue); // get the access modifier of color int mod2 = field1.getModifiers(); // convert the access modifier to string String modifier2 = Modifier.toString(mod2); System.out.println("Modifier: " + modifier2); ) catch (Exception e) ( e.printStackTrace(); ) ) )
Output
Value: brown Modifier: private
In the above example, we have created a class named Dog. The class contains a private field named color. Notice the statement.
Field field1 = obj.getDeclaredField("color"); field1.setAccessible(true);
Here, we are accessing color and assigning it to the object field1 of the Field
class. We then used field1 to modify the accessibility of color and allows us to make changes to it.
We then used field1 to perform various operations on the private field color.
To learn more about the different methods of Field, visit Java Field Class (official Java documentation).
3. Reflection of Java Constructor
We can also inspect different constructors of a class using various methods provided by the Constructor
class. For example,
import java.lang.Class; import java.lang.reflect.*; class Dog ( // public constructor without parameter public Dog() ( ) // private constructor with a single parameter private Dog(int age) ( ) ) class Main ( public static void main(String() args) ( try ( // create an object of Dog Dog d1 = new Dog(); // create an object of Class // using getClass() Class obj = d1.getClass(); // get all constructors of Dog Constructor() constructors = obj.getDeclaredConstructors(); for (Constructor c : constructors) ( // get the name of constructors System.out.println("Constructor Name: " + c.getName()); // get the access modifier of constructors // convert it into string form int modifier = c.getModifiers(); String mod = Modifier.toString(modifier); System.out.println("Modifier: " + mod); // get the number of parameters in constructors System.out.println("Parameters: " + c.getParameterCount()); System.out.println(""); ) ) catch (Exception e) ( e.printStackTrace(); ) ) )
Output
Constructor Name: Dog Modifier: public Parameters: 0 Constructor Name: Dog Modifier: private Parameters: 1
In the above example, we have created a class named Dog. The class includes two constructors.
We are using reflection to find the information about the constructors of the class. Notice the statement,
Constructor() constructors = obj.getDeclaredConstructor();
Burada, Dog'da bulunan tüm yapıcılara erişiyor ve bunları Constructor
türün bir dizi kurucusuna atıyoruz .
Daha sonra kurucu hakkında farklı bilgiler elde etmek için c nesnesini kullandık.
- c.getName () - kurucunun adını döndürür
- c.getModifiers () - yapıcının erişim değiştiricilerini tamsayı biçiminde döndürür
- c.getParameterCount () - her kurucuda bulunan parametrelerin sayısını döndürür
Constructor
Sınıfın daha fazla yöntemi hakkında bilgi edinmek için Constructor sınıfını ziyaret edin