public class Book {
private final static String TAG = "BookTag" ;
private String name;
private String author;
@Override
public String toString ( ) {
return "Book{" +
"name='" + name + '\'' +
", author='" + author + '\'' +
'}' ;
}
public Book ( ) {
}
private Book ( String name, String author) {
this . name = name;
this . author = author;
}
public String getName ( ) {
return name;
}
public void setName ( String name) {
this . name = name;
}
public String getAuthor ( ) {
return author;
}
public void setAuthor ( String author) {
this . author = author;
}
private String declaredMethod ( int index) {
String string = null;
switch ( index) {
case 0 :
string = "I am declaredMethod 1 !" ;
break ;
case 1 :
string = "I am declaredMethod 2 !" ;
break ;
default :
string = "I am declaredMethod 1 !" ;
}
return string;
}
}
public class ReflectClass {
private final static String TAG = "peter.log.ReflectClass" ;
public static void reflectNewInstance ( ) {
try {
Class< ? > classBook = Class. forName ( "com.android.peter.reflectdemo.Book" ) ;
Object objectBook = classBook. newInstance ( ) ;
Book book = ( Book) objectBook;
book. setName ( "Android进阶之光" ) ;
book. setAuthor ( "刘望舒" ) ;
Log. d ( TAG, "reflectNewInstance book = " + book. toString ( ) ) ;
} catch ( Exception ex) {
ex. printStackTrace ( ) ;
}
}
public static void reflectPrivateConstructor ( ) {
try {
Class< ? > classBook = Class. forName ( "com.android.peter.reflectdemo.Book" ) ;
Constructor< ? > declaredConstructorBook = classBook. getDeclaredConstructor ( String. class , String. class ) ;
declaredConstructorBook. setAccessible ( true ) ;
Object objectBook = declaredConstructorBook. newInstance ( "Android开发艺术探索" , "任玉刚" ) ;
Book book = ( Book) objectBook;
Log. d ( TAG, "reflectPrivateConstructor book = " + book. toString ( ) ) ;
} catch ( Exception ex) {
ex. printStackTrace ( ) ;
}
}
public static void reflectPrivateField ( ) {
try {
Class< ? > classBook = Class. forName ( "com.android.peter.reflectdemo.Book" ) ;
Object objectBook = classBook. newInstance ( ) ;
Field fieldTag = classBook. getDeclaredField ( "TAG" ) ;
fieldTag. setAccessible ( true ) ;
String tag = ( String) fieldTag. get ( objectBook) ;
Log. d ( TAG, "reflectPrivateField tag = " + tag) ;
} catch ( Exception ex) {
ex. printStackTrace ( ) ;
}
}
public static void reflectPrivateMethod ( ) {
try {
Class< ? > classBook = Class. forName ( "com.android.peter.reflectdemo.Book" ) ;
Method methodBook = classBook. getDeclaredMethod ( "declaredMethod" , int . class ) ;
methodBook. setAccessible ( true ) ;
Object objectBook = classBook. newInstance ( ) ;
String string = ( String) methodBook. invoke ( objectBook, 0 ) ;
Log. d ( TAG, "reflectPrivateMethod string = " + string) ;
} catch ( Exception ex) {
ex. printStackTrace ( ) ;
}
}
}