Reflection in Java ()

Source: Internet
Author: User

There are three ways to get class objects in Java

1.getClass (); But the downside is that if there is no class, it will go wrong and compile

2.class.forname ("Package + Class");//If there are no classes, this method will not error, but will run with an error

3. Package + Class. class

Instantiate with Reflection

Class<?> cls = Class.forName ("Class + package"= Cls.newinstance ();

Get the package that contains the class:

     Getpackage (); // return--type package name
getpackage (). GetName (); Return package Name

Get class Name:

class // Return package name + class name class. Getsimplename (); // Return class name

Get Parent class:

class. Getsuperclass.getsimplename ();

Get the class interface:

Class<?> CLS [] = cls.getinterfaces ();  for (...) {    cls[i].getsimplename ();}

Get the construction method:

Java.lang.reflect Package: GetConstructors (); // returns all construction getconstructor (param); // returns the specified construct
Constructors.getmodifiers ();//Get method modifiers
Constructors.getname ();//Get Construction method name
Constructors.getparametercount ();//Gets the number of construction method arguments
Constructors.getparametertypes ();//Gets the parameter type of the constructor method
Constructors.getexceptiontypes ();//Gets the exception type of the constructed method

Method of Acquisition:

GetMethods (); // gets all the methods in the class GetMethod (name,class<?>); // gets the specified method both return java.lang.reflect.method;getname (); // returns the method name getmodifiers (); // returns the method modifier getparametertypes (); // return Parameter type Invoke (Object,object ...); // invokes the specified method, invokes it with an instantiated object, and then sets the parameter;
Getreturntype ();//return value type
Getdeclaredmethods ();//Get methods in this class

Reflection in Java ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.