JavaFX教程-反射

梧桐雨—168發表於2008-03-18


JavaFX類、屬性、操作可以通過如下方式反射:

 public class Class {
  public attribute Name: String;
  public attribute Documentation:String?;
  public attribute Superclasses: Class* inverse Class.Subclasses;
  public attribute Subclasses: Class* inverse Class.Superclasses;
  public attribute Attributes: Attribute* inverse Attribute.Scope;
  public attribute Operations: Operation* inverse Operation.Target;
  public function instantiate();
 }

 public class Operation extends Class {
  public attribute Target: Class? inverse Class.Operations;
 }

 public class Attribute {
  public attribute Name: String;
  public attribute Documentation: String?;
  public attribute Scope: Class? inverse Class.Attributes;
  public attribute Type: Class?;
  public attribute Inverse: Attribute* inverse Attribute.Inverse;
  public attribute OneToOne: Boolean;
  public attribute ManyToOne: Boolean;
  public attribute OneToMany: Boolean;
  public attribute ManyToMany: Boolean;
  public attribute Optional: Boolean;
 }
JavaFX支援通過class操作符對類、屬性、成員函式和操作的進行反射訪問:

 import java.lang.System;

 System.out.println(1.class.Name) // prints "Number"
 System.out.println("Hello".class.Name); // prints "String"

 class X {
  attribute a: Number;
 }
 var x = new X();
 System.out.println(x.class.Name); // prints "X"
 System.out.println(sizeof x.class.Attributes); // prints 1
 System.out.println(x.class.Attributes[0].Name); // prints "a"
對屬性值進行反射訪問時,如果訪問運算元是屬性,則使用[]操作符:

 import java.lang.System;

 class X {
  attribute a: Number;
 }
 var x = new X();
 x.a = 2;
 System.out.println(x[x.class.Attributes[Name == 'a']]); // prints 2
 // the above statement is equivalent to this non-reflective code:
 System.out.println(x.a);
在JavaFX中,類的成員函式和操作本身被模式化作為在目標類中的類,而形參和返回值被表示為屬性。代表目標物件的屬性名是“this”。代表返回值的屬性名為“return”。代表形參的屬性具有和形參相同的屬性名。

譯者注:這裡的目標類是指使用成員函式和操作的類。而目標物件則指使用成員函式和操作的物件。

從上例中可以發現,你也可以從Class物件中獲取相同的、被反射的操作。

被反射的操作能夠像函式那樣通過將目標物件作為第一個引數、其它引數作為後面的引數的方式被呼叫:

 import java.lang.System;

 class X {
  operation foo(n: Number): Number;
 }

 var x = new X();
 var p = x.class.Operations[Name == 'foo'];
 System.out.println(op(x, 100));

 // the above code is equivalent to the following non-reflective code:
 System.out.println(x.foo(100));
bean屬性和Java類的公共欄位被反射為JavaFX屬性。但是,Java方法不能被反射為JavaFX操作。如果你想呼叫某個Java方法,那麼你可以通過簡單地使用Java API來實現。

注意:與Java不同的:在JavaFX中class操作符被用於表示式,而不是用於型別名(type name)。因此作為補充,JavaFX支援從型別名中獲取反射類物件的語法:

 :TypeName
For example:

 import java.lang.System;
 System.out.println(:System.Name); // prints "java.lang.System"
 System.out.println(:System.class.Name); // prints "Class"

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/13270562/viewspace-209699/,如需轉載,請註明出處,否則將追究法律責任。

相關文章