Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Reflection Method Error

I'm trying to figure out Reflection with this Android class:

Class<?> c = Class.forName("com.android.internal.widget.LockPatternUtils");
Method method = c.getDeclaredMethod("getKeyguardStoredPasswordQuality");
method.setAccessible(true);
Object object = method.invoke(c); // Error with this line
result = object.toString());

The method getKeyguardStoredPasswordQuality is declared as (no parameters):

public int getKeyguardStoredPasswordQuality() {
    // codes here
}

The error I got is:

Exception: java.lang.IllegalArgumentException: expected receiver of type com.android.internal.widget.LockPatternUtils, but got java.lang.Class<com.android.internal.widget.LockPatternUtils>

How do I declare com.android.internal.widget.LockPatternUtils as a receiver?

like image 938
ChuongPham Avatar asked Nov 02 '13 10:11

ChuongPham


People also ask

What is reflection in Android?

Reflection allows programmatic access to information about the fields, methods and constructors of loaded classes, and the use of reflected fields, methods, and constructors to operate on their underlying counterparts, within encapsulation and security restrictions.

Why use reflection in Java?

Reflection is a feature in the Java programming language. It allows an executing Java program to examine or "introspect" upon itself, and manipulate internal properties of the program. For example, it's possible for a Java class to obtain the names of all its members and display them.

What is Java reflection API?

Reflection is an API that is used to examine or modify the behavior of methods, classes, and interfaces at runtime. The required classes for reflection are provided under java.lang.reflect package which is essential in order to understand reflection.

How to create an instance of a class in Java reflection?

We can use newInstance() method on the constructor object to instantiate a new instance of the class. Since we use reflection when we don't have the classes information at compile time, we can assign it to Object and then further use reflection to access it's fields and invoke it's methods.


1 Answers

You are passing the class to #invoke() instead of an instance of LockPatternUtils.

You can create an instance using #newInstance().

like image 188
Keppil Avatar answered Oct 13 '22 12:10

Keppil