Java 反射常用方法樣本

來源:互聯網
上載者:User

標籤:class   java   反射   

<pre name="code" class="java">import java.lang.reflect.Constructor;import java.lang.reflect.Field;import java.lang.reflect.Method;class Point{int x;private int y;public Point(){x = 1;y = 2;}public void setX(int x) {this.x = x;}public void setY(int y) {this.y = y;}private Point(int x){this();this.x = x;}public Point(int x, int y) {super();this.x = x;this.y = y;}public void printPoint(){System.out.println("x = " + x + " , y = " + y);}}public class ReflectTest2 {public static void main(String[] args) throws Exception {//使用第一種方法建立對象Class cls1 = Class.forName("Point");Constructor con1 = cls1.getConstructor(int.class,int.class);Point p1 = (Point) con1.newInstance(5,6);p1.printPoint();//使用第二種方法建立對象Class cls2 = Point.class;Point p2 = (Point) cls2.newInstance();//無參建構函式p2.printPoint();//使用第三種方法建立對象Class cls3 = p1.getClass();//使用p1對象的setX方法將x值修改為10Method m1 = cls3.getMethod("setX", int.class);m1.invoke(p1, 10);p1.printPoint();/* * Note: * getDeclaredConstructor可以返回指定參數的建構函式, * 而getConstructor只能放回指定參數的public的建構函式  * */Constructor con2 = cls3.getDeclaredConstructor(int.class);//訪問私人變數、函數需要設定accessiblecon2.setAccessible(true);Point p4 = (Point) con2.newInstance(3);p4.printPoint();//Field f1 = cls3.getField("y");//errorField f1 = cls3.getDeclaredField("y");f1.setAccessible(true);//擷取p1的y值System.out.println(f1.get(p1));}}



 

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Java 反射常用方法樣本

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.