Topics Index

Creating reflect pakage Method

If you need explanation Read this topic

If you need Answer Take test on this topic

Creating reflect pakage Method
What is the output of the following program?
import java.lang.reflect.*;

public class Reflect {
    public static void main(String[] args) {
        Class noparams[] = {};
        Class[] paramString = new Class[1];
        paramString[0] = String.class;
        Class[] paramInt = new Class[1];
        paramInt[0] = Integer.TYPE;
        try {
            Class cls = Class.forName("AppTest");
            Object obj = cls.newInstance();
            Method method = cls.getDeclaredMethod("printIt", noparams);
            method.invoke(obj, null);
            method = cls.getDeclaredMethod("printIt", paramString);
            method.invoke(obj, new String("Merit Campus"));
            method = cls.getDeclaredMethod("setCounter", paramInt);
            method.invoke(obj, 999);
            System.out.println(cls.getDeclaredField(cls.getDeclaredFields()[0].getName()).getInt(obj));// LINE A
        } catch (Exception ex) {
class AppTest {
    static int counter1;
    public void printIt() {
        System.out.println("No Params");
    public void printIt(String temp) {
        System.out.println("String Param: " + temp);
    protected void setCounter(int counter) { // BLOCK A
        System.out.println("setCounter: " + counter);
        counter1 = counter++;

A. No Params
String Param: Merit Campus
setCounter: 999
B. No Params
String Param: Merit Campus
setCounter: 999
C. Compilation Error at LINE A
D. Compilation Error in BLOCK A, because static variables can be initialized only in static block.
E. Runtime Error
Topic: Advanced Java Programming Concepts

If you need explanation Read this topic

If you need Answer Take test on this topic

User comments below. All of them might not be correct.

ans d
static var initializd ly once
compilation err

Posted by Maheshwari Natarajan    2014-08-21 12:42:00

answer e runtime err.
bcz static variable again initialized insind try block

Posted by NagaRaj Nataraj    2014-08-21 12:46:14

Ans is A..  instead of directly creating object and calling methods, here we are making use of reflection api to do that.

Posted by Krishna Sai    2014-08-21 13:00:11

Ans is B...1st no argument printIt wil cal and printed and next printIt string wil caleed and Mc wil printerd and next 999 wil printed and again 999 bcz we are using post incrementing so incremented valued wont assign

Posted by Uday Kumar    2014-08-21 13:13:42

Congratulations Uday Kumar. You are this dose winner. We will send you the link using which you can claim your recharge.

Posted by Merit Campus    2014-08-22 05:14:11

© meritcampus 2019

All Rights Reserved.

Open In App