logo
down
shadow

How to find variable name from a list of class in a package


How to find variable name from a list of class in a package

By : Vijay Kundhiya
Date : November 22 2020, 02:59 PM
This might help you I think you should use reflection and use regular expression to match your case
code :
public static void match(String name,String line)
{   

      String pattern = "("+name+".)([a-z][A-Z]\\w+)";
      // line = "private java.lang.String com.poc.Example.mName";
      // Create a Pattern object
      Pattern r = Pattern.compile(pattern);

      // Now create matcher object.
      Matcher m = r.matcher(line);
      if (m.find( )) {
       /*  System.out.println("Found value: " + m.group(0) );
         System.out.println("Found value: " + m.group(1) );
        System.out.println("Found value: " + m.group(2) );*/
        list.add(m.group(1)+m.group(2));
      } 
}       public static void getFields(String className)
{
    //Field fields[]=a.getClass().getDeclaredFields();
    Field fields[];
    try {
        fields = Class.forName(className).getDeclaredFields();
        for(Field f:fields)
        {
            //System.out.println(f.toString());
            match(className,f.toString());
        }
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }catch (ExceptionInInitializerError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (MissingResourceException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }


}
public class Main {
private static List<String> list = new ArrayList<String>();
private static List<String> name = new ArrayList<String>();

public static String getSubPackage(String packageName) {
    try {
        getClassNamesFromPackage(packageName);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    packageName = packageName.replace("/", ".");
    packageName = packageName.substring(0, packageName.lastIndexOf('.'));
    return packageName;
}

public static List<String> getClassNamesFromPackage(String packageName)
        throws IOException, URISyntaxException {
    ClassLoader classLoader = Thread.currentThread()
            .getContextClassLoader();
    URL packageURL;

    packageName = packageName.replace(".", "/");

    packageURL = classLoader.getResource(packageName);
    if (packageURL == null)
        System.out.println(packageName);
    if (new URI(packageURL.toString()) == null)
        System.out.println(packageURL);
    URI uri = new URI(packageURL.toString());

    File folder = new File(uri.getPath());
    // won't work with path which contains blank (%20)
    // File folder = new File(packageURL.getFile());
    File[] content = folder.listFiles();
    // System.out.println(folder);
    String entryName;
    for (File actual : content) {
        entryName = actual.getName();
        if (entryName.contains(".class")) {
            // System.out.println(entryName);
            // System.out.println(entryName.substring(0,
            // entryName.lastIndexOf('.')));
            entryName = entryName.substring(0, entryName.lastIndexOf('.'));

            // System.out.println(actual.getName());

            name.add(packageName.replace("/", ".") + "." + entryName);
        } else {
            if (!(entryName.contains(".xml"))
                    && !(entryName.contains(".properties"))
                    && !(entryName.contains(".wsdl"))
                    && !(entryName.contains(".mine"))
                    && !(entryName.contains(".r15857"))
                    && !(entryName.contains(".r15939"))) {
                packageName = packageName.replace("/", ".");
                packageName = packageName + "." + entryName;
                packageName = getSubPackage(packageName);
            }
        }

    }

    return name;
}

public static void match(String name, String line) {

    String pattern = "(" + name + ".)([a-z][A-Z]\\w+)";
    // line = "private java.lang.String com.poc.Example.mName";
    // Create a Pattern object
    Pattern r = Pattern.compile(pattern);

    // Now create matcher object.
    Matcher m = r.matcher(line);
    if (m.find()) {
        /*
         * System.out.println("Found value: " + m.group(0) );
         * System.out.println("Found value: " + m.group(1) );
         * System.out.println("Found value: " + m.group(2) );
         */
        list.add(m.group(1) + m.group(2));
    }

}

public static void getFields(String className) {
    // Field fields[]=a.getClass().getDeclaredFields();
    Field fields[];
    try {
        fields = Class.forName(className).getDeclaredFields();
        for (Field f : fields) {
            // System.out.println(f.toString());
            match(className, f.toString());
        }
    } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ExceptionInInitializerError e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (MissingResourceException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    // System.out.println(a.getClass().getName());

}

@SuppressWarnings("rawtypes")
public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
    // Example a = new Example();
    // Example1 b = new Example1();

    // Class exmple = a.getClass().getDeclaredFields();
    String packageName = "com.oneassist";
    getClassNamesFromPackage(packageName);
    System.out.println(name.size());
    Iterator<String> iterator = name.iterator();
    System.out.println(name);
    String className = "";
    while (iterator.hasNext()) {
        className = iterator.next();
        // Class act = Class.forName(packageName+"."+className);
        // getFields(act);

        // System.out.println(className);
        /*
         * Class cls = Class.forName(className);
         * 
         * @SuppressWarnings("unchecked") Constructor ctor =
         * cls.getConstructor(); Object object = ctor.newInstance();
         */

        // System.out.println(className);
        getFields(className);

    }
    System.out.println(list);
    System.out.println("size =" + list.size());
}


Share : facebook icon twitter icon
SSIS Package: Can't convert System.Object to List(Of String) for storage in Package variable?

SSIS Package: Can't convert System.Object to List(Of String) for storage in Package variable?


By : razvacpop
Date : March 29 2020, 07:55 AM
wish help you to fix your issue The problem is that the Users variable has never been set to a List(Of String) - but it's not Nothing, either. Instead, SSIS has helpfully initialized it to a System.Object, which of course can't be cast to a List(Of String).
code :
Public Sub Main()
    Dim msg As String
    If Dts.Variables("Users").Value Is Nothing Then
        msg = "Dts.Variables(""Users"").Value is Nothing"
    Else
        msg = "Dts.Variables(""Users"").Value is an object of type " + Dts.Variables("Users").Value.GetType().FullName
    End If
    Dts.Events.FireInformation(0, "Main", msg, "", 0, True) ' Information: Dts.Variables("Users").Value is an object of type System.Object

    ' rest of your code follows
android app crashes at startup, Logcat: Didn't find class "[package name]" at /data/app/[package name]

android app crashes at startup, Logcat: Didn't find class "[package name]" at /data/app/[package name]


By : Darren Lee
Date : March 29 2020, 07:55 AM
it should still fix some issue some suggestions
1) declare activity in AndroidManifest.xml file if not declared yet.
code :
07-29 03:49:46.734: E/AndroidRuntime(837): Caused by: java.lang.ClassNotFoundException: Didn't find class "com.example.calculate.firsttry.**MainActivity**" // here it says MainActivity not found, Check the name of your activity
Why can't Java Reflection find the package-private constructor of a class in another package?

Why can't Java Reflection find the package-private constructor of a class in another package?


By : user2206088
Date : March 29 2020, 07:55 AM
Any of those help I have the following API code, shortened for brevity: , Class#getConstructor(Object...) javadoc states
naming practice of variables in java. why class variable not package variable

naming practice of variables in java. why class variable not package variable


By : Amzinino
Date : March 29 2020, 07:55 AM
seems to work fine The class is basically the frame or blueprint for creating instances (objects). Static variables and methods are defined inside the frame and created when the class is loaded by the ClassLoader, so no instance needs to be created for them to exist. That's why they are class variables. They are not package variables because they belong specifically to that class. I.e. you would access them by calling MyClass.myVariable.
Instance variables only come into existence when an instance of the class i.e. an object is created by calling new(), and they are specific to that object and not specific to the class. There are as many counts of an instance variable as the number of objects of that class are created, whereas there is always just one count of the static class variable. That is why they are called instance variables, because they are specific to an instance and not to the class.
cannot find package private (default) class in separate file in a different name in same package

cannot find package private (default) class in separate file in a different name in same package


By : Scotty
Date : March 29 2020, 07:55 AM
wish help you to fix your issue javac will automatically compile all the linked file used in the file you are compiling if there .class files are not found. Like in your case ABC.java. But one thing to notice is javac will not search for all the files with .java extension to be compiled. But it will look for the file name with the same name as the class. Like in your case T1.
So if you will compile T.java and then compile ABC.java it will run as expected. But if you compile ABC.java and not T.java compiler will not find T1.class then it will look for T1.java, but it will not found it too, which will give you an error. On the other hand if you will rename T.java to T1.java it will work as expected.
Related Posts Related Posts :
  • How to query using objectify in Google App Engine app
  • List value is printing address instead of value
  • StringUtils.isBlank return false for null Strings
  • Sent parameter through PATCH android
  • i am not able to clear the code below given using throwable concept in java
  • How to get System time instead of Server time in java?
  • How to push json data into an arrya object in MONGO DB by java
  • Saving RelationshipEntity not working
  • Error on "instanceOf" when checking a subClass
  • Java - Splitting a image into 4 images
  • "Pinging" a server in Java
  • RoboGuice Proguard CreationException
  • Android Array list returns Null after adding values
  • Jar Executable what am I doing wrong?
  • How do I mitigate Connection leak triggered for connection com.mysql.jdbc.JDBC4Connection@11d08960,
  • How do i iterate values from a 2d array using conditions
  • Hide Button in CustomPagerAdapter
  • Java GC: does it ever make sense to call super.finalize() in a class that only extends Object?
  • 64bit HashMap in Java
  • Hibernate wildcard query on two columns
  • Want to Generate Auto Login Program Using Java
  • Spring security Oauth 2 with ajax login and form login
  • Parse findInBackground doesn't add to global arraylist?
  • Remove random item from ArrayList
  • in SpringMVC getMessage from i18n properties in a function outside the controller
  • How do I add JCheckBox next to each name that has been entered into an arraylist from a JTextField?
  • Return node ID along with complete node
  • InvocationTargetException. Cannot cast class X to class X. When invoked in Scala Imain through spark-submit
  • how to print elements of a 1D array into a N x N box
  • How to map csv file to pojo class in java
  • How, in Java, to encode default vhost %2F in URL/URI so it doesn't get changed to slash and fail to work
  • Tomcat 5.5 https configuration in Windows Server 2008 64bit
  • Enabling FIPS 140-2 compliance mode in MULE ESB
  • How to pass String PackageName to PkgName under parseXML() and run XMLParser class as a new activity when click on list
  • Error while creating spring -hibernate configuration file
  • Hand off control between java threads
  • NoClassDefFoundError: scala/collection/Seq
  • Getting stack overflow error on one machine but not the other on the same code
  • How can I loop AsyncAjaxRequest in GWT?
  • Failed to find provider info for urbanairship.provider
  • Android ListView Adapter Crash issue/Duplicates
  • Displaying Splash screen only once on user preference
  • Loop List<WebElement> doesn't stop despite no more WebElements
  • Check if pattern exists in a String
  • Swing - Key Problems (Arrow Keys, Tab, etc.) in GUIs with TextComponents
  • Why the solution for binary search tree validity is not working?
  • Double encrypting 2048 RSA?
  • create junit test for runnable class
  • Unable to read and sort information from a text file in Java
  • My device isn't getting detected in android studio (driver issue)
  • Representing a Graph in Java
  • How to XML mapping using jxls
  • Quick Sort stackoverflow error for large arrays
  • Parsing Apache Tika XML Output returns Unknown Tag
  • java simple UI loop, can't find bug
  • how to use greater than and less than in a single if statement in java
  • Error:(27, 13) Failed to resolve: com.antonyt.infiniteviewpager:library:1.0.0
  • Gradle dependencies on source set of different projects
  • Session Scope in Restful Spring Services
  • Java: Change a value in an overridden method of a different class to a value that was calculated in the class
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co