> Java > java지도 시간 > 본문

자바 getMethod()

PHPz
풀어 주다: 2024-08-30 15:39:49
원래의
1032명이 탐색했습니다.

Java getMethod()는 java.lang.Class.getMethod()의 메소드로, 지정된 클래스 객체 참조에 있는 지정된 공용 멤버 함수의 참조를 보유하는 java.lang.reflect 패키지의 Method 클래스 인스턴스를 반환합니다. 클래스나 인터페이스에. 이 메소드는 첫 번째 매개변수로 전달되는 데 필요한 메소드의 이름을 사용합니다. 전달될 두 번째 매개 변수는 반환된 메서드의 형식 매개 변수 데이터 유형을 결정하는 Class 객체의 배열이거나 null을 paramterTypes로 결정하는 빈 배열입니다. 여기에 사용된 검색 알고리즘은 private GetPublicMethods() 메서드와 동일합니다.

광고 이 카테고리에서 인기 있는 강좌 JAVA MASTERY - 전문 분야 | 78 코스 시리즈 | 15가지 모의고사

무료 소프트웨어 개발 과정 시작

웹 개발, 프로그래밍 언어, 소프트웨어 테스팅 등

getMethod()는 아래와 같이 3가지 유형의 예외를 발생시킵니다.-

  1. NoSuchMethodException
  2. NullPointerException
  3. 보안예외

구문

아래는 java.lang.Class의 getMethod 시그니처입니다

public Method getMethod(String name, Class<?>... parameterTypes)
throws NoSuchMethodException, SecurityException
로그인 후 복사
  • public: 이 키워드는 프로젝트의 모든 클래스에서 지정된 메서드에 액세스할 수 있는지 여부를 결정합니다.
  • 반환 유형 메서드: 이 메서드는 이름이 인수로 전달된 필수 메서드를 참조하는 메서드 클래스의 인스턴스를 반환합니다.
  • 매개변수:
  • 이름 이 매개변수는 참조하는 클래스 또는 인터페이스 객체에 있는 메서드 이름의 문자열 표현을 나타냅니다. 클래스에 해당 메서드가 없으면 NoSuchMethodException이 발생합니다. 그렇지 않으면 알고리즘이 실행되고 메서드가 반환됩니다.
  • parameterTypes: name 매개변수의 메소드가 인수로 요구하는 데이터를 가리키는 클래스 유형 객체의 배열을 나타냅니다. 이 배열의 크기는 지정된 메소드 이름에 필요한 인수에 따라 다릅니다. 메소드에 인수가 필요하지 않으면 이 인수에 null이 전달됩니다.

아래와 같은 수업 데모가 있는 경우:

class Demo{
public void method1(String a){
System.out.println(a);
}
}
로그인 후 복사

그러면 getMethod 호출은 다음과 같습니다.

Demo demoObj= new Demo();// Object of Demo class
Class cObj= demoObj.getClass()
Class [] carr = new Class[1];
carr[0] = String.class;// class reference to java.lang.String class stored In the array of type Class
Method mObj = cObj.getMethod("method1",carr);
로그인 후 복사

Java에서 getMethod()는 어떻게 작동하나요?

getMethod()는 참조 클래스 또는 인터페이스 객체의 지정된 메소드에 Method 인스턴스를 반환합니다.

  • 지정된 클래스나 인터페이스에서 찾아야 하는 공용 메서드의 이름을 보유하는 문자열 데이터 유형의 이름 매개변수를 사용합니다. 또한 찾고 있는 함수에 대한 인수 유형을 나타내는 클래스 객체 배열을 사용합니다.
  • JVM은 두 인수를 읽고 java.lang.Class의 privateGetPublicMethods() 메소드에서 사용된 것과 동일한 검색 알고리즘을 수행하고 지정된 이름을 가진 공용 메소드가 존재하는지 검색합니다. 클래스에 두 개 이상의 메서드가 있는 경우 더 구체적인 반환 유형을 가진 메서드가 반환됩니다. 그렇지 않으면 방법이 임의로 선택됩니다.

메서드를 찾은 경우 해당 참조를 보유하는 메소드 클래스의 인스턴스를 반환합니다.

지정된 메서드에 인수가 필요하지 않으면 매개변수 유형 대신 null이 전달됩니다. 이는 이름이 같지만 인수의 수나 데이터 유형이 다른 메서드가 두 개 이상 있는 메서드 오버로드의 경우에 도움이 됩니다. 이 메서드는 3가지 유형의 예외를 발생시킵니다.-

1. NoSuchMethodException: 이 유형의 예외는 JVM이 클래스 또는 인터페이스에서 지정된 이름을 가진 메소드를 찾을 수 없을 때 발생합니다.

2. SecurityException: 이 유형의 예외는

  • checkMemberAccess(this, Member.PUBLIC)가 호출되어 이에 대한 액세스가 거부됩니다.
  • 호출자 클래스 로드는 현재 클래스의 조상 로더와 다릅니다. 따라서 SecurityManagers.checkPackageAccess()가 호출됩니다. 따라서 패키지에 대한 액세스가 거부됩니다.

3. NullPointerException: 인수의 메서드 이름 대신 null이 전달되면 발생합니다.

Java getMethod() 구현 예

다음은 언급된 예시입니다.

예시 #1

이 예에서는 Office 클래스의 두 메서드(객체를 요구하는 메서드와 인수를 필요로 하지 않는 메서드)에 대한 getMethod 호출의 출력을 보여줍니다.

//package Proc;
import java.lang.reflect.*;
class Office{
public String OfficeLocation() {
return location;
}
public String getEmpName(Integer eid) {
return"Sergio";
}
String location = "Bangalore";
}
public class prac1 {
public static void main(String[] args) {
Office ofc = new Office();
Class cObj = ofc.getClass();
Class[] carr = new Class[1];
carr[0] = Integer.class;
try {
Method meth = cObj.getMethod("OfficeLocation", null);
System.out.println("Method with specified name is = " + meth.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
}
try {
Method meth = cObj.getMethod("getEmpName", carr);
System.out.println("Method with specified name is = " + meth.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
}
}
}
로그인 후 복사

출력:

자바 getMethod()

예시 #2

이 예에서는 JVM이 주어진 이름을 가진 클래스인 개인 메소드를 찾을 수 있는지 확인합니다.

//package Proc;
import java.lang.reflect.*;
public class prac1 {
public static void main(String[] args) {
Office ofc = new Office();
Class cObj = ofc.getClass();
try {
Method meth = cObj.getMethod("OfficeLocation", null);
System.out.println("Method with specified name is = " + meth.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
}
}
}
class Office{
private String OfficeLocation() {
return location;
}
public String getEmpName(Integer eid) {
return "Sergio";
}
String location = "Bangalore";
}
로그인 후 복사

출력:

자바 getMethod()

Example #3

In this example , we will see how different exceptions occur when a non-existing method is called, and null is passed in the method’s name.

//package Proc;
import java.lang.reflect.*;
class Office{
public String OfficeLocation() {
return location;
}
public String getEmpName(Integer eid) {
return "Sergio";
}
String location = "Bangalore";
}
public class prac1 {
public static void main(String[] args) {
Office ofc = new Office();
Class cObj = ofc.getClass();
Class[] carr = new Class[1];
carr[0] = Integer.class;
try {
Method meth = cObj.getMethod("show", null);
System.out.println("Method found " + meth.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
}
try {
Method meth = cObj.getMethod(null, carr);
System.out.println("Method found" + meth.toString());
} catch(NoSuchMethodException e) {
System.out.println(e.toString());
}catch(NullPointerException e) {
System.out.println(e.toString());
}
}
}
로그인 후 복사

Output:

자바 getMethod()

Conclusion

Java.lang.getMethod() is a method used to search if a method with the given name and type of arguments is present in the class or not. It uses the same algorithm to find the method used in the privateGetPublicMethods() method. JVM search for the given public method and returns a Method instance; otherwise, NoSuchMethodException is raised.

위 내용은 자바 getMethod()의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!